Sahat Yalkabov
Sahat Yalkabov

Reputation: 33664

Java - events within events?

I have a textfield and a button.

They have identical actionPerformed event listener. (e.g. when user clicks a button and when user hits ENTER).

Is there a way to avoid this kind of duplication of code? It just becomes a pain in the __ modifying the code in 2 places for each such case.

I was thinking would it be possible to call a button event inside of a textfield event, analogous like calling a function inside of another function?

EDIT:

Passing the same addActionPerformed method call to both textfield and button did the trick.

Upvotes: 0

Views: 101

Answers (2)

Sascha
Sascha

Reputation: 947

    ActionListener actionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //...
        }
    };
    Button button = new Button();
    button.addActionListener(actionListener );
    TextField  textField = new TextField();
    textField.addActionListener(actionListener);

or not so elegant but possible call a third method doIt() in your both actionPerformed() methods

Upvotes: 2

MeBigFatGuy
MeBigFatGuy

Reputation: 28568

I assume you are complaining because you are using an anonymous inner class for both. So don't do that. Create a first-class class, and create an instance that you pass to both component's addActionListener.

Upvotes: 4

Related Questions