JReno
JReno

Reputation: 357

JButton actionPerformed in another class

Say I have a class Client that has a function Client.Function1(). How do I get my JButton in class LoginGUI to have it do Function1 in the Client class?

I don't want to initialize a Client instance in the LoginGUI class.

Upvotes: 1

Views: 1446

Answers (1)

Sweeper
Sweeper

Reputation: 271555

I will demonstrate how you use an action listener in a singleton class.

class Client implements ActionListener {
    private static Client instance = new Client();
    public static Client getInstance() { return instance; }

    public void actionPerformed(ActionEvent e) {
        // do the thing you want to do here.
    }
}

And when you create the JButton:

JButton b = new JButton();
// configure your button here...
b.addActionListener(Client.getInstance());

It is as simple as that.

What if you also want to change the UI and stuff when the button is pressed?

Just add another action listener!

First, write a method in the GUI class and write whatever you want to do with the UI when the button is pressed:

public void actionPerformed(ActionEvent e) {
    // do stuff
}

After that, make the GUI class implement ActionListener.

Then, just add another action listener:

b.addActionListener(this);

Upvotes: 1

Related Questions