gpt4 book ai didi

java - 如何重新加载 Java Swing GUI?

转载 作者:行者123 更新时间:2023-12-02 09:28:08 24 4
gpt4 key购买 nike

每次触发函数时,我都需要刷新 GUI。这就是我定义 GUI 框架的方式:

public class GUI {

private JFrame frame;

/**
* Launch the application.
*/
public static void runGui() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setSize(800, 600);
window.frame.setTitle("My Title");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public GUI() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
//CODE
}

因此,GUI.runGui() 函数在如下函数中被调用:

public void myFunction()
{
//CODE
GUI.runGui();
}

问题如下:每次调用此函数时,它都会生成一个新的 GUI 实例,因此我最终会拥有多个实例。这不是我想要的,因为我只需要刷新 GUI 的内容,而 GUI 必须只有一个。我认为问题出在建筑上。有办法解决这个问题吗?

最佳答案

看看 runGui 正在做什么:每次调用它时它都会创建并初始化一个 GUI。将一次性初始化代码从 runGui 中取出并放入您运行一次的另一个位置(如初始化方法)。在 runGui 中访问您想要刷新的组件(可能是内容 Pane ):

// This needs to become an instance method (non static) in this example in
// order to access the frame
public void runGui() {
EventQueue.invokeLater(new Runnable() {
public void run() {
// Refresh your component here. Here I'm redrawing the
// content pane

frame.getContentPane().repaint();
}
});
}

关于java - 如何重新加载 Java Swing GUI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58187624/

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