Treesin
Treesin

Reputation: 73

How do you change the functionality of a method from outside of the class?

Sorry for the confusing title, but I have no idea how to phrase this in under a sentence. What I want to do is have a menu system of "buttons" that do different things when clicked (pause, end, go to a different menu, etc). The only ways I can think of doing this are

a) Have a million subclasses, which is bad

b) Have a million if-statements, which is also bad

Ideally, I would like something where I can just declare the new instance of the class, and then add in the method at the same time, kind of like how the keyAdaptor works.

Thanks in advance!

~Tree

Upvotes: 4

Views: 85

Answers (3)

Óscar López
Óscar López

Reputation: 236150

A nice solution would be to have a single class and pass the method as a parameter, as is possible in functional programming languages. For the time being this is not possible, but look forward to Java 8's Lambda Expressions. For example, something like this will be possible:

public class MyButton implements ActionListener {

    private ActionListener handler;

    public MyButton(ActionListener lambda) {
        handler = lambda;
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        handler(event);
    }

}

And you will be able to create new buttons like this:

MyButton but1 = new MyButton(e -> /* do something */);
MyButton but2 = new MyButton(e -> /* do something else */);

Similarly, it'll be possible to directly add an action listener to an existing JButton:

button.addActionListener(e -> /* do something */);

Another more verbose, but currently available option would be to pass the action listener as an anonymous class parameter, and override the relevant method(s), as shown in @Basilio German's answer.

Upvotes: 1

Basilio German
Basilio German

Reputation: 1819

you can have a single class with lots of different buttons, and have each button do a different thing. here is the code for a JButton to do something specific:

    JButton exampleButton= new JButton("Click me!");
    exampleButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //Do something when the button is clicked
        }
    });

Of course, you would call play(), stop(), or whatever you want from inside it

Upvotes: 1

brazilianldsjaguar
brazilianldsjaguar

Reputation: 1449

You should be able to use the button class and have different handlers for each button. There would be a different function for every different thing you wanted the buttons to do, but a the buttons themselves could all the be same class.

Upvotes: 3

Related Questions