簡體   English   中英

Java:訪問動作偵聽器內部的變量

[英]Java: Access a variable which is inside an actionlistener

我已經嘗試了一段時間來訪問我的主類中的變量:

public class Results extends JFrame {
     public static void main(String[] args) 
     {
        System.out.println(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(){
    private int doble;
    public void actionPerformed(ActionEvent ae){
                doble++;
                System.out.println("Doubles: " + doble);
                }
  });
}

我已經嘗試了5種方法來做到這一點,但這似乎是不可能的。 有什么想法嗎?

嘗試將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是一個非靜態字段,因此您需要使用Results的具體實例來訪問它。 查看我對您的main()方法所做的更改。
  • 像這樣直接訪問私有字段並不表示封裝很干凈,實際上會生成編譯器警告。
  • 使用非字雙人間 ,以避免對保留字的編譯器錯誤可能不是像你一樣的東西更有意義的像

希望這可以幫助。

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

main()是靜態的, doble是實例變量。 您必須實例化或將變量設為靜態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM