Java Swing 快捷鍵

Java  Swing 快捷鍵html

 

給Java Swing 編程中按鈕或者其餘組件事件添加快捷鍵的方法java

Component.setAccelerator(KeyStroke.getKeyStroke(‘Q’, InputEvent.CTRL_MASK));編程

這個快捷鍵是ctrl+Q,經過這個方法便可實現點擊操做與ctrl+Q快捷鍵操做一樣的效果this

 

爲JButton設置ctrl快捷鍵spa

this.jButton_save.registerKeyboardAction(new SaveListener(), KeyStroke.getKeyStroke( KeyEvent.VK_S, KeyEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);code

爲JButton/JRadioButton/JCheckBox設置Alt助記符component

 使用從JComponent繼承下來的方法。button.setMnemonic(KeyEvent.VK_M);htm

 

 

爲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>");

相關文章
相關標籤/搜索