user3042022
user3042022

Reputation: 87

Java listeners - easier way?

I am having troubles with my code. I was wondering if there was an easier way to use listeners instead of constantly having to do this:

example.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {

            if (example.isSelected()) { 
                System.out.println("Example is selected");

So I do this for every radio button which means I have to constantly repeat the same code over and over. Right now it might be easy but lets say I use over 100 radio buttons. I would then have to repeat it over and over. Is there an easier way to do this?

Here is my code which I am using, you can find some of these in there:

Upvotes: 0

Views: 83

Answers (4)

Phil Freihofner
Phil Freihofner

Reputation: 7910

You can use the same ActionListener for all buttons. I'm assuming you know how to create and use a single ActionListener. To differentiate the Buttons, I'd consider giving each a unique ActionCommand string, to simplify the branching logic. The ActionEvent that is passed will expose the ActionCommand string via getActionCommand().

public void actionPerformed(java.awt.event.ActionEvent evt) {
    String cmd = evt.getActionCommand();

    // now, inspect and branch on cmd
}

Upvotes: 0

Ian McLaird
Ian McLaird

Reputation: 5585

Yes, there's a better way. Stop using the anonymous class, and create an actual ActionListener class.

public class RadioButtonActionListener implements ActionListener {
    private JRadioButton radioButton;
    private String message;

    public void actionPerformed(ActionEvent evt) {
        if (this.radioButton.isSelected()) {
            System.out.println(message);
        }
    }

    public RadioButtonActionListener(JRadioButton button, String msg) {
        this.radioButton = button;
        this.message = msg;
    }
}

Then set it up like this

faktura.addActionListener(new RadioButtonActionListener(faktura, "Fakturering vald"));

Upvotes: 0

ifloop
ifloop

Reputation: 8386

If you're using Java8 you might consider using Lambdas:

example.addActionListener(e -> {
    System.out.println("You clicked the button");
});

See OracleDocs - Lambda Expressions for detailed information about this.
See Lambda Expressions for ActionListeners for a small tutorial matching your question.

Upvotes: 1

DWilches
DWilches

Reputation: 23015

You can define the ActionListener before using it, so you can make this instead:

ActionListener myListener = new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == radioButton1) { 
            ...
        } else if (evt.getSource() == radioButton2) { 
            ...
        }
}

And then use it wherever you want:

radioButton1.addActionListener(myListener);
radioButton2.addActionListener(myListener);

Upvotes: 1

Related Questions