Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JButton

 
Sagar Bilgi
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check out the doClick() method which JButton inherits from AbstractButton.
 
Sagar Bilgi
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wouldnt I still need to listen on that key though?
 
Kanu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic