开发者

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.


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.


    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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜