3

你好,我有一个带有 CardLayout 和 3 张卡片的 Jframe。我在第一张卡片上的按钮上有一个 ActionListener。

这段代码运行良好:

JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        CardLayout cl = (CardLayout)(cards.getLayout());
        cl.show(cards, "wait");
    }
}

问题是当我添加代码以在服务器上进行登录时(我正在开发一个 xmpp 客户端):

JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        CardLayout cl = (CardLayout)(cards.getLayout());
        cl.show(cards, "wait");
        xmppManager = new Xmpp("jabberserver", 5222);
        try {
            xmppManager.init();
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        cl.show(cards, "userList");
    }
}

基本上,当用户按下登录按钮时,我需要显示“请稍候”卡,进行登录,然后显示另一张卡。但在这种情况下,“等待”卡不显示,它会登录(大约需要 5 秒),并直接显示最终卡“userList”。

我错过了什么?

4

2 回答 2

5

All the code is executing on the Event Dispatch Thread which is preventing the GUI from repainting itself. You need the call to the server to execute in a separate Thread so you don't block the EDT.

Read the section from the Swing tutorial on Concurrency for more information and a suggested solution.

于 2011-02-17T16:27:23.370 回答
1

显示后可能需要触发屏幕重绘,请稍候?它可能不会自动触发。

于 2011-02-17T16:07:57.550 回答