简体   繁体   中英

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:

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.

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);

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"));

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
}

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