gpt4 book ai didi

java - 访问 ActionListener 类中的 Gui,使用计时器每 x 秒更新一次

转载 作者:行者123 更新时间:2023-12-01 13:31:15 25 4
gpt4 key购买 nike

我想每 30 秒更新一次 Swing Gui,其中一些标签将从数据库连接获取新值。到目前为止,我每次都尝试创建一个新的 Gui 并处理旧的 Gui,但这不是一个优雅的解决方案,而且无论如何也不起作用。

 public class Gui extends JFrame {

private boolean open;
//setter, getter
public Gui() {
JPanel pane = new JPanel(new BorderLayout());
int numberOfRows = 9;
int numberOfColumns = 2;
pane.setLayout(new GridLayout(numberOfRows, numberOfColumns));

String wState;
if(open){wState="Window open";}
else{wState="Window closed";}
JLabel windowState= new JLabel(wState);
pane.add(windowState);
new Timer(5000, new WindowState()).start(); }

private class WindowState implements ActionListener {
public void actionPerformed(ActionEvent e) {
Gui g = new Gui();
g.setOpen(true);
}

我知道它不会像这样工作,但我希望我能清楚地知道我想做什么。问题是我无法访问 actionPerformed() 方法中的 Gui 元素。我只想使用在 actionPerformed() 方法中检索到的新值来更新 windowState Label。

最佳答案

"The problem is that I cannot access the Gui elements in the actionPerformed() method."

您需要了解变量作用域。目前,所有变量都在构造函数中本地作用域

public class GUI {
public GUI {
JPanel panel = new JPanel(); <--- Locally scoped
}
}

您需要为要访问的对象提供全局范围

public class GUI {
JPanel panel= new JPanel(); <--- global scope

public GUI(){
}
}

然后您可以访问 actionPerformed 中的面板

<小时/>

看这里

import java.awt.BorderLayout;
import java.awt.GridLayout;
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.SwingUtilities;
import javax.swing.Timer;

public class GUI extends JFrame {

private boolean open;
JPanel pane;
JLabel windowState;
int count = 1;

public GUI() {

int numberOfRows = 9;
int numberOfColumns = 2;
pane = new JPanel(new BorderLayout());
pane.setLayout(new GridLayout(numberOfRows, numberOfColumns));

String wState;
if (open) {
wState = "Window open";
} else {
wState = "Window closed";
}

windowState = new JLabel(wState);
pane.add(windowState);

add(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
new Timer(500, new WindowState()).start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUI();
}
});
}

private class WindowState implements ActionListener {

public void actionPerformed(ActionEvent e) {
count++;
windowState.setText("Number " + count + "!");
}
}
}

关于java - 访问 ActionListener 类中的 Gui,使用计时器每 x 秒更新一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21552417/

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