This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doing same job on two or more events

 
saurabh agr
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JButton print=new JButton("Print");

print.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("hello");
//other codes
}
});

print.addKeyListener(new KeyAdapter()
{
public void keyPressed(keyEvent e)
{
if(e.getKeyCode()==10) // trap enter key press
{
// i want here to do the same job of button clicking, which is defined in actionPerformed() method
}
}
});

i have created a JButton object and add action listener to it, defined actionPerformed() method, now i want that the same job will also be done when some one presses enter key on the JButton without writing the code again. How can i do this???

i want to know is there any way or any method which can automatically generate button click event?
 
Maneesh Godbole
Saloon Keeper
Posts: 10971
11
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While posting code, please UseCodeTags

You do not need the key listener. The action performed is triggered if the user clicks on the button or hits Enter when it has focus
 
Maneesh Godbole
Saloon Keeper
Posts: 10971
11
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question would be more suitable on the UI forums. Moving thread.
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maneesh Godbole wrote:The action performed is triggered if the user clicks on the button or hits Enter when it has focus

Actually not. Space yes, Enter no.

I'd use an InputMap / ActionMap pair:
 
Michael Dunn
Ranch Hand
Posts: 4632
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
another alternative is to set the button as the default button

frame.getRootPane().setDefaultButton(print);

so whenever you press enter (except for when components that use enter have focus e.g. textArea) the actionListener fires
 
saurabh agr
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all of you for your kind support.......
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic