gpt4 book ai didi

java - 更新 Java Swing 中的主要 GUI 元素

转载 作者:行者123 更新时间:2023-12-02 07:08:33 25 4
gpt4 key购买 nike

我正在尝试更新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
}
});
}

最佳答案

我从你的问题中了解到,你认为静态意味着不可更改。对于 Java 来说情况并非如此。在 Java 中,永不改变的对象和组件被称为final

保持 main 简单且小,并在 doThings(); 中进行循环和更改

这是一个计时器,用于更新 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;
}

关于java - 更新 Java Swing 中的主要 GUI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15817474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com