It's not a secret anymore!*
The moose likes Swing / AWT / SWT and the fly likes JButton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JButton" Watch "JButton" New topic
Author

JButton

Sagar Bilgi
Ranch Hand

Joined: Apr 26, 2001
Posts: 37
simple question,
I have a jbutton, how do I simulate a button click on that button..nothing in the API seems obvious..I need something like a set Accelerator Method.( I dont want to use Mnemonics)..when the user clicks on the left arrow button on the Keyboard I want to trigger that buttons action.
Is there anyway to do this apart from implementing ur own Key Listener for that button?
Thanks
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
check out the doClick() method which JButton inherits from AbstractButton.


Rob
SCJP 1.4
Sagar Bilgi
Ranch Hand

Joined: Apr 26, 2001
Posts: 37
wouldnt I still need to listen on that key though?
Kanu
Greenhorn

Joined: Feb 26, 2002
Posts: 1
The place where you have created a JButton:
JButton jb =new JButton();
jb .addActionListener(this);
Then, write a method,
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==jb)
{
//you can type here the cod that you want to write, when the object //gets clicked.
}
}
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Sagar, yes, you have to add a listener to capture the keypress, and in response call the doClick() method of your button.
Remus Stratulat
Greenhorn

Joined: Jan 29, 2002
Posts: 14
Here is something that I think will help you. I spent some time looking at BasicButtonListener and BasicButtonUI and come up with this:
// setting the to receive action when F3 is pressed
InputMap keyMap = new ComponentInputMap(Btn);
keyMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), "action");
ActionMap actionMap = new ActionMapUIResource();
actionMap.put("action", new HelpAction());
SwingUtilities.replaceUIActionMap(Btn, actionMap);
SwingUtilities.replaceUIInputMap(Btn, JComponent.WHEN_IN_FOCUSED_WINDOW, keyMap);
// setting done
From now on the button is pressed every time you hit F3, whatever the focused component.


strem
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: JButton