java swing调用button,使用swing在java中为JButton创建热键

I use the following code to create hot keys for the java form using swing. If I press ALT+N,ALT+R,ALT+1,ALT+2 the cursor moves to correct text fields and I enter the value in corresponding Text Fields. It works properly. My problem is, I have Save and exit JButtons in this form if. I press CTRL+S means the Save button will be selected at the same time If i press CTRL+X means the exit button will be selected. How to create mnemonics for JButton? How to do CTRL+S,CTRL+X this using the following code?

Thanks in advance.

package hotkeys;

import java.awt.event.*;

import javax.swing.*;

import java.net.*;

public class hotkey extends JFrame {

public static void main(String arg[]) {

JLabel Name = new JLabel("Name");

JTextField tf1 = new JTextField(20);

Name.setLabelFor(tf1);

Name.setDisplayedMnemonic('N');

JLabel Regno = new JLabel("RegNO");

JTextField tf2 = new JTextField(20);

Regno.setLabelFor(tf2);

Regno.setDisplayedMnemonic('R');

JLabel Mark1 = new JLabel("Mark1");

JTextField tf3 = new JTextField(20);

Mark1.setLabelFor(tf3);

Mark1.setDisplayedMnemonic('1');

JLabel Mark2 = new JLabel("Mark2");

JTextField tf4 = new JTextField(20);

Mark2.setLabelFor(tf4);

Mark2.setDisplayedMnemonic('2');

JButton b1 = new JButton("Save");

JButton b2 = new JButton("eXit");

JFrame f = new JFrame();

JPanel p = new JPanel();

p.add(Name);

p.add(tf1);

p.add(Regno);

p.add(tf2);

p.add(Mark1);

p.add(tf3);

p.add(Mark2);

p.add(tf4);

p.add(b1);

p.add(b2);

f.add(p);

f.setVisible(true);

f.pack();

}

}

解决方案

You need to register a keyBinding in the button's component inputmap. In code (repeating a subtle variant of what you have been told to do in your previous questions :-)

// create an Action doing what you want

Action action = new AbstractAction("doSomething") {

@Override

public void actionPerformed(ActionEvent e) {

System.out.println("triggered the action");

}

};

// configure the Action with the accelerator (aka: short cut)

action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));

// create a button, configured with the Action

JButton toolBarButton = new JButton(action);

// manually register the accelerator in the button's component input map

toolBarButton.getActionMap().put("myAction", action);

toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(

(KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值