0

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's pretty much it. Not quite sure whether there's another problem here. Maybe posting code would allow us to see if there's some issue.
2
    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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.