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



我希望我的按钮"licz":将信息的文本值更改为"加载",执行某些操作并将"info"更改为"完成"。('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
            }
        }
    });

但是程序先制作"某物",将"信息"标签更改为"加载",然后立即更改为"完成",如何保留这些以防万一?

actionPerforming 的事件在事件处理线程上处理,并且应快速终止以获得响应式 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");
    });
});

最新更新