如何在外面的按钮短语中使用变量?

时间:2016-05-06 12:00:47

标签: java

我正在尝试构建一个程序,它有一个按钮,一个标签,它给了我多少次点击按钮。但该计划中的其他一些地方也需要这个数字。这就是为什么我想知道如何第二次应用变量?

    jb.addActionListener(new ActionListener()
            {



                @Override
                public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub\
                        number = 0;
                        number++;
                        .......
                    }

          });
     .......
    //String s = "good" + number;
    //jf.setText(s);
    // How to have the variable "number" be still avaliable here?

   }// end of some method...

public static void main(String[] args) {
    button2 t = new button2();
}

}

3 个答案:

答案 0 :(得分:0)

number声明为私有字段,并在单击按钮时增加number的值。您的代码会将number的值重置为0(零),每次单击该按钮,然后向其添加1,结果number始终等于1.

private int number;

jb.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {
    number++;
  }
};

public static void main(String[] args) {
  button2 t = new button2();
}

答案 1 :(得分:0)

将您的number声明为类/静态变量,然后您可以访问它。

同样参考,

class SomeName{
private static int number = 0;
......

jb.addActionListener(new ActionListener()
            {



                @Override
                public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub\
                        number = 0;
                        number++; // here you can access number without any issue.
                        .......
                    }

          });

 .......
    String s = "good" + number; // here you can access number without any issue.
    jf.setText(s);

   }// end of some method...


}

答案 2 :(得分:0)

我认为您的应用程序的问题是您希望在初始化JFrame期间访问号码,但您应该在actionListener方法中执行此操作。初始化应该只运行一次,当您单击按钮时,它将不再运行。以下是有关其工作原理的代码示例:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class button2 extends JFrame {

    int num = 0;
    JButton b;
    JTextField jtf;

    public button2()
    {
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b = new JButton("Clickme");
        jtf = new JTextField("");
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                num++;
                jtf.setText("good " + num);
                System.out.println("This prints every time I click the button");
            }
        });


        System.out.println("This only prints once");

        //String s = "good" + number;
        //jf.setText(s);  <--- Moved into the actionListener
        // How to have the variable "number" be still available here?

        this.setLayout(new GridLayout(0,1));
        this.add(jtf);
        this.add(b);
        this.pack();
    }
    public static void main(String...banana) { new button2(); }
}