简体   繁体   English

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

[英]How can I change JLabel text during work of JButton?

I would like my button 'licz' to: change text value of info to ''loading'', do something and change 'info' to "done". 我希望按钮“ licz”能够:将信息的文本值更改为“正在加载”,执行某些操作,然后将“信息”更改为“完成”。 ('licz' is here a JButton, 'info' JLabel) (“ 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
            }

        }
    });

But the program makes "something" first, changes 'info' label to "loading" and immediately to "done", how to keep these in case? 但是该程序首先进行“某些操作”,将“信息”标签更改为“正在加载”,然后立即更改为“完成”,以防万一?

The event of actionPerformed is handled on the event handling thread, and should terminate fast to have a responsive GUI. actionPerformed事件是在事件处理线程上处理的,应快速终止以具有响应性GUI。 Hence call invokeLater . 因此,调用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");
            }
        });
    }
});

Or in java 8: 或在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");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM