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

时间:2011-12-21 10:09:54

标签: java swing

我使用以下代码使用swing为java表单创建热键。如果我按ALT + N,ALT + R,ALT + 1,ALT + 2,光标将移动到正确的文本字段,并在相应的文本字段中输入值。它工作正常。我的问题是,我保存并以这种形式退出JButton如果。我按CTRL + S表示同时选择保存按钮如果按CTRL + X表示将选择退出按钮。如何为JButton创建助记符?如何使用以下代码执行CTRL + S,CTRL + X?

提前致谢。

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();
    }
}

4 个答案:

答案 0 :(得分:18)

您需要在按钮的组件输入映射中注册keyBinding。在代码中(重复你在之前的问题中被告知要做的微妙变体: - )

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

答案 1 :(得分:9)

Sun对整个Key Binding问题有很好的描述。你可以在这里找到它:

JavaSE Tutorial on Keybinding

//修改

编辑了我的示例代码,因此您只需复制+粘贴它即可。包括缺失的要点,感谢您的反馈。

KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK); 
Action performSave = new AbstractAction("Save") {  
    public void actionPerformed(ActionEvent e) {     
         //do your save
         System.out.println("save");
    }
}; 
JButton b1 = new JButton(performSave); 
b1.getActionMap().put("performSave", performSave);
b1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "performSave"); 

KeyStroke keyExit = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK); 
Action performExit = new AbstractAction("Exit") {  
    public void actionPerformed(ActionEvent e) {     
        //exit
        System.out.println("exit");
    }
}; 
JButton b2 = new JButton(performExit); 
b2.getActionMap().put("performExit", performExit);
b2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyExit, "performExit"); 

答案 2 :(得分:1)

刚刚修改了你的代码。 (在 ** 中插入代码)
只需1条评论... Ctrl-X是编辑命令“剪切”的快捷方式(以及Ctrl-C和Ctrl-V)。您在框架中有可编辑的字段。我改用了Ctrl-Q(退出)。

import java.awt.event.*;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.plaf.ActionMapUIResource;

import java.net.*;

public class HotKeys 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);

    // *****************************************************
    ActionMap actionMap = new ActionMapUIResource();
    actionMap.put("action_save", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Save action performed.");
        }
    });
    actionMap.put("action_exit", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Exit action performed.");
        }
    });

    InputMap keyMap = new ComponentInputMap(p);
    keyMap.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
            java.awt.Event.CTRL_MASK), "action_save");
    keyMap.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q,
            java.awt.Event.CTRL_MASK), "action_exit");
    SwingUtilities.replaceUIActionMap(p, actionMap);
    SwingUtilities.replaceUIInputMap(p, JComponent.WHEN_IN_FOCUSED_WINDOW,
            keyMap);
    // *****************************************************

    f.add(p);
    f.setVisible(true);
    f.pack();
}
}

答案 3 :(得分:0)

我和其他人一样,为我提供这样的学习体验。我一直难以应用我过去发现的密钥绑定的代码片段,我希望我的解释和代码能够清楚。感谢@kleopatra的代码片段,我的代码基于以下代码。

(我使用大写字母,我不应该为了更清楚地显示必须匹配的东西。)

代码通过Ctrl-Shift-UactionPerformed中的匹配字符串将MYACTION次按键与getInputMap getActionMap中的代码相关联。

下面的MYACTION的三个实例必须匹配,MYACTIONBUTTON的四个实例必须匹配,字符串MAKE_THESE_MATCH的两个实例必须匹配。称呼他们你会做什么;只是让它们匹配。

按钮MYACTIONBUTTON必须MYACTION作为JButton定义它的参数,并且必须getInputMapgetActionMap

private static JButton MYACTIONBUTTON;
private static JFrame frame;
private static JPanel panel;

...

Action MYACTION = new AbstractAction()
{

  @Override
  public void actionPerformed(ActionEvent e)
  {
      // put action code here
  }
};

MYACTIONBUTTON = new JButton(MYACTION);

MYACTIONBUTTON.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)

                           .put(getKeyStroke(VK_U, CTRL_DOWN_MASK | SHIFT_DOWN_MASK),

                                  "MAKE_THESE_MATCH"); 

MYACTIONBUTTON.getActionMap().put("MAKE_THESE_MATCH",        MYACTION);

panel.add(MYACTIONBUTTON);

frame.add(panel);