在方法

时间:2016-02-29 02:17:25

标签: java swing user-interface

我设置了GUI,以便按下按钮b1时:

 public class CubeCalc  {

 static int next = 0;

 public static void MakeTitlePage()
 {
  final JFrame window = new JFrame("Cubic Feet Calculator"); //Creates Frame

  JButton b1 = new JButton("Start");
  b1.setBackground(Color.decode("#5A20DF"));
     b1.setForeground(Color.WHITE);
     /*b1.setLayout(new GridBagLayout());*/
     b1.setPreferredSize(new Dimension(150,50));
  b1.addActionListener(new ActionListener() { // action when button is pressed
            int pressCount=0;
            @Override
            public void actionPerformed(ActionEvent e) {

                window.dispose();
               next = 1;


            }
        });

然后它将处理标题页,并且next将等于一,并且在事件调度线程上,它创建一个新页面来执行其他操作:

public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() { // launch frame on the Event Dispatch Thread
            @Override
            public void run() {
                 MakeTitlePage();

                 if (next==1)
                 {
                   MakeCalcPage();
                 }

                 System.out.println(next);
            }
        });
 }

问题是变量next仍然等于零,即使我在方法MakeTitlePage()中更改了它。如何在所有方法中更改变量,而不仅仅是那个?

1 个答案:

答案 0 :(得分:0)

我认为您可能误解了事件派发线程的工作原理。当您向组件添加侦听器时,您告诉Swing侦听某些事件并在事件派发线程上调用关联的侦听器。如果您使用静态变量next在线程之间进行通信,那么首先,这不是执行此操作的方式,其次,您正在与同一个线程进行通信。

如果您希望按钮关闭当前窗口并打开一个新窗口,那么您应该直接在actionPerformed方法中执行此操作:

public void actionPerformed(ActionEvent e) {
    window.setVisible(false);
    showCalculationFrame();
}