如何在JButton工作期间更改JLabel文本?

时间:2014-12-28 16:47:07

标签: java jframe jbutton jlabel

我希望我的按钮'licz':将信息的文本值更改为''loading'',执行某些操作并将'info'更改为“done”。 ('licz'在这里是一个JButton,'info'JLabel)

        licz.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            info.setText("Loading..."); // Here
            if(go())
            {   
                brute(0);
                info.setText("Done!"); //here
                if(odwrot)
                    JOptionPane.showMessageDialog(frame, "good");
                else
                    JOptionPane.showMessageDialog(frame, "bad");
            }
            else
            {
                JOptionPane.showMessageDialog(frame, "bad");
                info.setText("Done"); // And here
            }

        }
    });

但该程序首先制作“东西”,将“信息”标签更改为“加载”并立即更改为“完成”,如何保留这些以防万一?

1 个答案:

答案 0 :(得分:1)

actionPerformed事件在事件处理线程上处理,应该快速终止以具有响应GUI。因此请致电invokeLater

licz.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        info.setText("Loading...");
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                boolean good = false;
                if (go())
                {   
                    brute(0);
                    good = odwrot;
                }
                JOptionPane.showMessageDialog(frame, good ? "good" : "bad");
                info.setText("Done");
            }
        });
    }
});

或者在java 8中:

licz.addActionListener((e) -> {
    info.setText("Loading...");
    EventQueue.invokeLater(() -> {
        boolean good = false;
        if (go())
        {   
            brute(0);
            good = odwrot;
        }
        JOptionPane.showMessageDialog(frame, good ? "good" : "bad");
        info.setText("Done");
    });
});