Java Swing 快捷键
给Java Swing 编程中按钮或者其他组件事件添加快捷键的方法:
Component.setAccelerator(KeyStroke.getKeyStroke(‘Q’, InputEvent.CTRL_MASK));
这个快捷键是ctrl+Q,通过这个方法即可实现点击操作与ctrl+Q快捷键操作同样的效果
为JButton设置ctrl快捷键
this.jButton_save.registerKeyboardAction(new SaveListener(), KeyStroke.getKeyStroke( KeyEvent.VK_S, KeyEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
为JButton/JRadioButton/JCheckBox设置Alt助记符
使用从JComponent继承下来的方法。button.setMnemonic(KeyEvent.VK_M);
为JMenuItem添加快捷键
openJMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
mnuFileNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
快捷键:alt + 1
给菜单加上助记符 mnuFile.setMnemonic(‘F’);
JLabel & setLabelFor(Component c)
JLabel可以透过setDisplayedMnemonic(char aChar)方法来设定辅助键,以及设定辅助键时必须同时使用setLabelFor(Component c)方法指定这个标签所伴随的组件,也就是当使用者使用辅助键时,焦点也会转移到所指定的组件上。
示例代码如下(快捷键为Alt + U),注意使用方法的顺序:
JLabel userLabel = new JLabel("User:");
userLabel.setDisplayedMnemonic('U');
JComboBox user = new JComboBox(new String[]
{ "1","2","3" });
userLabel.setLabelFor(user);
userPanel.add(userLabel,BorderLayout.WEST);
userPanel.add(user,BorderLayout.CENTER);
JTabbedPane使用助记符在不同JComponent中切换
tabPane.add(title,JComponent component);
---------------------use the method setMonicAt(int tabIndex, int mnemonic) e.g.:
tabPane.setMnemonicAt(0,KeyEvent.VK_T); tabPane.setMnemonicAt(1,KeyEvent.VK_H);
Question: How to put the mnemonic under the second or third occured charater ? 怎么把助记符的显示下划线移动到特定位置上
For example: a JButton named button1 with text "Enter Time:" , set the mnemonic under 't' in the word "time"
so the code should be: (shoould write both )
button1.setMnemonic('T');
button1.setDisplayedMnemonicIndex(6);
Problem: cannot set mnemonic in JLabel/JComponent.text with HTML text 如果文本是html的,那么助记符的下划线不会显示,但是助记符响应正确
e.g.
JTextArea textArea =newJTextArea(10,20);
JLabel label =newJLabel("Text");
label.setLabelFor(textArea);
label.setDisplayedMnemonic(KeyEvent.VK_X);
vs
JTextArea textArea =newJTextArea();
JLabel label =newJLabel("<html>Text</html>");//!!! NO DECORATION
label.setLabelFor(textArea);
label.setDisplayedMnemonic(KeyEvent.VK_X);
Analyze分析: BasicLabelUI paints the label differently depending on whether it got HTML or not.If not , BasicLabelUI will call some of its own functions that draw the underline. If it does, BasicHTMLRenderer is used, that does not paint any underlines.
Solution: JLabel label = new JLabel("<html>Te<u>x</u>t</html>");