我正在尝试更新java swing应用程序中的主gui,因此有一个可运行的线程可以保持主gui可见,但问题是它在main中被调用,而main是一个静态函数。我想说Element.SetTtext。但是我要更新的所有调用都不是静态的。如何更新主GUI中的标签,...等?
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new AGC().setVisible(true);
// code to update labels here
}
});
}
答案 0 :(得分:1)
要求更清晰,何时需要更新标签?它是基于一个事件?
您始终可以保留要更新的组件的全局变量,并从事件处理程序访问它。
您能否使用代码更新您的问题,以便更清晰?
答案 1 :(得分:1)
我从你的问题中理解的是,你认为静态意味着不可改变。 Java不是这样。在Java中,永不改变的对象和组件被定义为 final 。
保持您的主要简单和小,并在doThings();
这是一个Timer,用于更新JLabel的文本:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Foo extends JFrame {
public Foo() {
jLabel1 = new JLabel("label 1");
jPanel1 = new JPanel();
jPanel1.add(jLabel1);
add(jPanel1);
pack();
// code to update whatever you like here
doThings();
}
private void doThings() {
// code to update whatever you like here
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
jLabel1.setText("foo " + (j++));
}
};
Timer timer = new Timer(500, actionListener);
timer.start();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Foo().setVisible(true);
}
});
}
private JLabel jLabel1;
private JPanel jPanel1;
private int j = 0;
}