简体   繁体   中英

How to access variables of a class in another class without making them static?

I am working on a Java Swing application and it has a JFrame which has array of JButton (Another class). I have variables in the JFrame which I want to access in the JButton when its ActionListener is called. Currently I am declaring those variables as static so that I can access them directly.

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
}

Here is the MyButton class:

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

But is there any other way to do this without declaring the variables and functions static?. I want to perform some logic based on the values in all buttons whenever ActionListener is invoked in any button

Note: I can't create JFrame object in the JButton class.

Make it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM