Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function Key Mnemonics

Status
Not open for further replies.

fatcodeguy

Programmer
Feb 25, 2002
281
CA
How do I set a function key (F1, F2, F3...) as a mnemonic (hot key) for a button/tabbed pane? Thanks

 
For a button :

JButton button = new JButton("Button");
button.setMneumonic('B'); //set char 'B' as the mneumonic

That's it! - ActionEvents from mneumonics are handled in exactly the same way as from clicks on the button.

Not sure about JTabbedPane, never used one !

Ben
 
Thanks, but what if you want to hit F4 and it presses the button. Any way to do that?
 
There is a (I think its called) KeyEventListener, or something like that, which you can set to do stuff when key is pressed. I'm at work now, and haven't got the code with me as its a while since I did it... I'll look it up tonight and get back to you. Thinking about it, this would prob be the best way to change the focus of the JTabbedPane aswell ...
 
I figured out how to do it for a JTabbedPane:
setMnemonicAt(INDEX,INT);
 
Hey ... told you I'd get back ...

the below class shows the way ... make sure in your code when you adapt it that you call the aKeyListener() method in you main() or whatever - it just sits in the background listening for specified key events.

By the way ... hint hint .. vote "helpful" on the "Mark this post as helpful/expert post!" link at bottom of page !!!!

PS - key identifiers are of the constants "KeyEvent.VK_BLA" - so the 'up arrow' key is VK_UP, f5 is VK_F5 etc...

Ben.


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class TestKey {
static JFrame f;
public static void main(String[] args) {
TestKey tk = new TestKey();
tk.aKeyListener();
}

public static void aKeyListener() {
f = new JFrame();
f.setSize(200, 200);
f.setVisible(true);
f.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
System.out.println("hello f4");
}
}
});
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top