在ActionListener类中访问Gui,使用Timer每隔x秒更新一次

时间:2014-02-04 12:20:58

标签: java swing user-interface

我想每隔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标签。

1 个答案:

答案 0 :(得分:1)

  

“问题是我无法访问actionPerformed()方法中的Gui元素。”

您需要了解变量范围。目前,所有变量都在构造函数

中本地作用域
public class GUI {
    public GUI {
        JPanel panel = new JPanel();  <--- Locally scoped
    }
}

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

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

    public GUI(){
    }
}

然后,您可以访问panel

中的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 + "!");
        }
    }
}