Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Same code for both ActionListener and MouseListener  RSS feed

 
Tony Chow
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I would like to ask if there is any simple way to apply the same code on both ActionListener and MouseListener, so that the same code is executed when the user either presses a JButton or presses Enter when a JTextField is focused.

I know that I can define a method, while it is not preferred as I may use break; in my MouseListener.

A simple example:


Although I can define a new method that prints out the three numbers, I have to add certain break; code in different cases. So I just wonder whether there is another way to do things like this.

Please help.

 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling a common method would seem the way to go. You could pass a boolean parameter to it that indicates whether it's been called from the ActionListener or from the MouseListener, and take different actions based on its value.
 
Campbell Ritchie
Marshal
Posts: 55681
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote: . . . You could pass a boolean parameter to it that indicates whether it's been called from the ActionListener or from the MouseListener, . . .
Or an enum constant; that way you can have more than two options. But only do that if the options are similar. Otherwise use different Listener objects.
 
Piet Souris
Rancher
Posts: 1979
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't do it this way. I would use two different Listeners, and put the
common code into a separate method, maybe driven by some specific parameter.

But what is the intention of having a MouseListener for your button? An 'enter'
on your textfield should have the same meaning as a press on the button?
If so, then only one actionListener is needed.

Greetz,
Piet
 
Rob Camick
Ranch Hand
Posts: 2800
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


You should not be using a MouseLIstener to handle mouse clicks on a button. You should just be using an ActionListener. Then the same ActionListener can be added to the button and the text field.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!