2013-01-17 25 views
0

我已经在努力了,而现在我的主类访问变量中:的Java:访问一个变量,它是一个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 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种方式来做到这一点,但似乎并不可行。有什么想法吗?

回答

2

尝试移动的双人间外的构造你的宣言,使之成为一个领域,像这样:

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); 
    } 

} 

一些评论:

  • 由于双人间是非静态字段,您需要使用Results的具体实例来访问它。看看我对main()方法所做的更改。
  • 像这样直接访问私有字段并不表示非常干净的封装并且实际上会产生编译器警告。
  • 使用非字双人间,以避免对保留字编译器错误可能不是像你一样的东西更有意义一样计数

希望这有助于。

+0

我会接受你的回答:)谢谢你。似乎我误解了一些东西!:) –

1

目前doble是在构造函数声明的局部变量,所以其范围只有confined to constructor,在insatnce level声明它在其他地方访问它。

public class Results extends JFrame { 
    private int doble; 
     //cons code 
    public static void main(String[] args) 
    { 
     System.out.println(new Results().doble); 
    }} 
+0

你是对的,但我必须接受第一个,因为它是一样的。 –

0

main()是静态的,doble是实例变量。你必须实例化,或使变量静态。