在动作事件期间在标签中设置文字 [英] set text in label during an action event

查看:40
本文介绍了在动作事件期间在标签中设置文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
几次通过单击按钮来更改标签文本摇摆不定

Possible Duplicate:
several times change label text by clicking button in swing not work

我正在使用Java Swing开发GUI,其中使用了两个组件JButton和JLabel. JLabel的文本最初设置为单击按钮".单击按钮后,我希望将JLabel的文本更改为"Processing".最后更改为"Processed"

I am using Java Swing to develop a GUI in which I use two components JButton and JLabel. The text of JLabel is initially set to "Click the button". After clicking the button I want the text of JLabel to change to "Processing".And finally to "Processed"

因此,当我单击按钮时,控件转到ActionPerformed,其中我已使用setText()方法将JLabel的文本设置为"Processing". ActionPerformed中的最后一条语句是使用setText()将JLabel的文本设置为已处理".

So, when I click the button the control goes to ActionPerformed wherein I have set the text of JLabel to "Processing" using setText() method. The last statement in ActionPerformed is setting the text of JLabel to "Processed" using setText().

当我运行程序时,标签显示单击按钮".最后,它变为已处理".但是,它永远不会显示正在处理".

When I run the program the label shows "Click the button".In the end it changes to "Processed". However, it never displays "Processing".

推荐答案

之所以不能立即使用,是因为处理GUI刷新的Java线程也处理了侦听器的事件.因此,当您调用setText()方法时,它会告诉GUI线程(事件调度线程称为EDT)更新组件,但由于EDT当前位于执行代码的方法中,因此目前无法完成

The reason because it is not working right now is that the Java thread that handle the GUI refreshing also handles the events of the Listeners. So when you call the setText() method it tells the GUI thread (called EDT for Event Dispatch Thread) to update the Component, but it can't be done right now because the EDT is currently in the actionPerformed() method executing your code.

因此,我认为您应该将可以执行任何工作的代码并在新线程中更改JLabel的文本.因此,EDT在actionPerformed()中启动它,然后在JLabel的文本更改时可以自由更新GUI.

So I think you should put the code that do whatever work and change the text of your JLabel in a new thread. So the EDT starts it in the actionPerformed() and is then free to update the GUI when the text of your JLabel changes.

类似这样的东西:(您必须实现run方法)

Something like this: (You have to implement the run method)

public void actionPerformed(ActionEvent e) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            myLabel.setText("Processing");
            //Do the job
            myLabel.setText("Processed");
        }     
    });
    t.start();
}

理想情况下,必须从EDT本身调用setText()方法和其他更改组件的方法,以避免错误……在我给您的示例中,情况并非如此.如果要执行此操作,请使用以下方法:

Ideally the setText() method and others that alter the component have to be called from the EDT itself to avoid bugs... This is not the case in the example I gave you. If you want to do it use this method:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        myLabel.setText("my text");
    }
});

这篇关于在动作事件期间在标签中设置文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆