2014-10-12 57 views
0

我正在研究Java Swing應用程序,它有一個JFrame,它有JButton(另一個類)的數組。當我調用ActionListener時,我想在JButton中訪問JFrame中的變量。目前我正在將這些變量聲明爲static,以便我可以直接訪問它們。如何訪問另一個類中的類的變量而不使其變爲靜態?

public class MyFrame extends JFrame { 
    //static variables 
    public static MyButton buttons[] = new MyButton[N]; 
    public static int counter = 0; 
    public static int clickedX, clickedY; 

    public static void main (String[] args) { 
     new MyFrame(); 
    } 

    public MyFrame(){ 
     // Doing Everything Here 
     setSize(300, 380); 
     setResizable(false); 
     setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
     // Layout, JMenu etc. 
    } 

    //static functions to access static variables Here 
} 

這裏是MyButton類:

public class MyButton extends JButton implements ActionListener { 

    private int xID,yID; 
    public MyButton(int x, int y) { 
     addActionListener(this); 
     xID = x; 
     yID = y; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     // Accessing MyFrame static variables and functions here  
    } 
} 

但是否有任何其他方式做到這一點不聲明變量和函數靜態?我想根據所有按鈕中的值執行一些邏輯,只要在任何按鈕中調用ActionListener即可

注意:我無法在JButton類中創建JFrame對象。

+0

注意'buttons'數組中的元素是永遠不會被初始化,它僅包含'null'元素 – msrd0 2014-10-12 10:10:53

回答

2

讓這樣的:

public class MyFrame extends JFrame implements ActionListener{ 
    //static variables 
    private JButton buttons[] = new JButton[N]; 
    private int counter = 0; 
    private int clickedX, clickedY; 

    public static void main (String[] args) { 
     new MyFrame(); 
    } 

    public MyFrame(){ 
     for (int i = 0; i < buttons.length; i++) 
     { 
      JButton b = new JButton(); 
      b.addActionListener(this); 
      buttons[i] = b; 
     } 
     // Doing Everything Here 
     setSize(300, 380); 
     setResizable(false); 
     setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
     // Layout, JMenu etc. 
    } 

    public void actionPerformed (ActionEvent e) { 
     // your code 
    } 
} 
+0

感謝您的回答,但有什麼辦法知道哪個按鈕被點擊? – Vivek 2014-10-12 10:24:51

+0

@Vivek'e.getSource()'將返回按鈕 – msrd0 2014-10-12 10:26:07

+0

耶現在就知道了。謝謝!! – Vivek 2014-10-12 10:30:25