java swing 按键_Java Swing 快捷键

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.

JTextAreatextArea=newJTextArea(10,20);JLabellabel=newJLabel("Text");label.setLabelFor(textArea);label.setDisplayedMnemonic(KeyEvent.VK_X);

vs

JTextAreatextArea=newJTextArea();JLabellabel=newJLabel("Text");//!!! NO DECORATIONlabel.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("Text");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值