File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes doing same job on two or more events Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "doing same job on two or more events " Watch "doing same job on two or more events " New topic
Author

doing same job on two or more events

saurabh agr
Ranch Hand

Joined: Apr 14, 2010
Posts: 37
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

Joined: Jul 26, 2007
Posts: 10523
    
    9

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


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10523
    
    9

This question would be more suitable on the UI forums. Moving thread.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
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

Joined: Apr 14, 2010
Posts: 37
Thanks to all of you for your kind support.......
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doing same job on two or more events