Java:访问actionlistener中的变量
我尝试访问主类中的变量已有一段时间了:Java:访问actionlistener中的变量,java,swing,constructor,actionlistener,Java,Swing,Constructor,Actionlistener,我尝试访问主类中的变量已有一段时间了: public class Results extends JFrame { public static void main(String[] args) { System.out.println(doble); }} 它在actionlistener中,就像这样 public Results () { // Create a JPanel for the buttons DOUBLE AND NOT DO
public class Results extends JFrame {
public static void main(String[] args)
{
System.out.println(doble);
}}
它在actionlistener中,就像这样
public Results ()
{
// Create a JPanel for the buttons DOUBLE AND NOT DOUBLE
JPanel duplicate = new JPanel(
new FlowLayout(FlowLayout.CENTER));
JButton doblebutton = new JButton("DOUBLE");
doblebutton.addActionListener(new ActionListener(){
private int doble;
public void actionPerformed(ActionEvent ae){
doble++;
System.out.println("Doubles: " + doble);
}
});
}
我试过5种方法,但似乎不可能。有什么想法吗 当前
doble
是构造函数中声明的一个局部变量,因此其作用域仅限于构造函数
,在检查级别
声明它以在其他地方访问它
public class Results extends JFrame {
private int doble;
//cons code
public static void main(String[] args)
{
System.out.println(new Results().doble);
}}
目前,
doble
是在构造函数中声明的一个局部变量,因此它的作用域仅限于构造函数,在检查级别
声明它以在其他地方访问它
public class Results extends JFrame {
private int doble;
//cons code
public static void main(String[] args)
{
System.out.println(new Results().doble);
}}
main()
是静态的,doble
是实例变量。您必须实例化或使变量为静态。main()是静态的,doble
是实例变量。您必须实例化变量或使变量为静态。尝试将您的doble声明移动到构造函数之外,使其成为一个字段,如下所示:
public class Results extends JFrame {
private int doble;
public Results() {
// Create a JPanel for the buttons DOUBLE AND NOT DOUBLE
JPanel duplicate = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton doblebutton = new JButton("DOUBLE");
doblebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
doble++;
System.out.println("Doubles: " + doble);
}
});
}
public static void main(String[] args) {
Results results = new Results();
System.out.println(results.doble);
}
}
一些评论:
- 由于doble是一个非静态字段,因此需要使用具体的结果实例来访问它。看看我对main()方法所做的更改
- 像这样直接访问私有字段并不表示封装非常干净,实际上会生成编译器警告
- 使用非单词doble来避免保留单词double上的编译器错误,可能不如使用更有意义的count更好
希望这能有所帮助。尝试将您的doble声明移动到构造函数之外,使其成为一个字段,如下所示:
public class Results extends JFrame {
private int doble;
public Results() {
// Create a JPanel for the buttons DOUBLE AND NOT DOUBLE
JPanel duplicate = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton doblebutton = new JButton("DOUBLE");
doblebutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
doble++;
System.out.println("Doubles: " + doble);
}
});
}
public static void main(String[] args) {
Results results = new Results();
System.out.println(results.doble);
}
}
一些评论:
- 由于doble是一个非静态字段,因此需要使用具体的结果实例来访问它。看看我对main()方法所做的更改
- 像这样直接访问私有字段并不表示封装非常干净,实际上会生成编译器警告
- 使用非单词doble来避免保留单词double上的编译器错误,可能不如使用更有意义的count更好
希望这有帮助。我会接受你的回答:)非常感谢。似乎我误解了一些事情!:)我会接受你的回答:)非常感谢。似乎我误解了一些事情!:)你也是对的,但我必须接受第一个,因为它是一样的。你也是对的,但我必须接受第一个,因为它是一样的。