Java Swing快捷键和按键绑定

1. 快捷键和助记符

设置Save菜单选项的快捷键为Ctrl+S:

JMenuItem save = new JMenuItem("Save");
save.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
                                           java.awt.Event.CTRL_MASK));
设置File和Save的助记符:

JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem save = new JMenuItem("Save");
save.setMnemonic('S');            // Always use a capital letter
file.add(save);

http://docstore.mik.ua/orelly/java-ent/jfc/ch03_08.htm


2. ActionMap()和InputMap()例子

1).

import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestBindKey
{
 JFrame jf=new JFrame("测试");
 JTextArea ta=new JTextArea(3,30);
 JButton bt=new JButton("发送");
 JTextField tf=new JTextField(15);
 public void init()
 {
  jf.add(ta);
  JPanel jp=new JPanel();
  jp.add(tf);
  jp.add(bt);
  jf.add(jp,BorderLayout.SOUTH);

  AbstractAction sendMsg=new AbstractAction()
  {
   public void actionPerformed(ActionEvent e)
   {
    ta.append(tf.getText()+"\n");
    tf.setText("");
   }
  };

  bt.addActionListener(sendMsg);
  //将Ctrl+Enter键和“send”关联
  tf.getInputMap().put(KeyStroke.getKeyStroke('\n',java.awt.event.InputEvent.CTRL_MASK),"send");
  //将"send"和sendMsg Action关联

  tf.getActionMap().put("send",sendMsg);
  
  jf.pack();
  jf.setVisible(true);
  
 }
 public static void main(String[] args)
 {
  new TestBindKey().init();
  System.out.println("ActionMap and InputMap!");
 }
}

2).

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.JTextComponent;

public class KeyBinding {
  public static void main(String[] argv) {
	JFrame frame = new JFrame(" Adding an InputMap to a Component");
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	JPanel panel = new JPanel();  
	JTextArea area = new JTextArea(7,10);
	JScrollPane pane = new JScrollPane(area);
	  
    InputMap im = area.getInputMap(JComponent.WHEN_FOCUSED);
    im.put(KeyStroke.getKeyStroke("F2"), "actionName");

    ActionMap am = area.getActionMap();
    am.put("actionName", new AbstractAction("actionName") {
      public void actionPerformed(ActionEvent evt) {
        //System.out.println((JTextComponent) evt.getSource());
    	  System.out.println("action1"+ evt.getID());
      }
    });
    im.put(KeyStroke.getKeyStroke("F3"), "actionName2");
    am.put("actionName2", new AbstractAction("actionName2") {
      public void actionPerformed(ActionEvent evt) {
        //System.out.println((JTextComponent) evt.getSource());
    	  System.out.println("action2"+ evt.toString());
      }
    });
    JButton component1 = new JButton("button 1");
    JButton component2 = new JButton("button 2");

    component1.setInputMap(JComponent.WHEN_FOCUSED, im);
    component2.setInputMap(JComponent.WHEN_FOCUSED, im);

    component1.setActionMap(am);
    component2.setActionMap(am);

    panel.add(pane);
    panel.add(component1);
    panel.add(component2);
    frame.add(panel);
    frame.setSize(400,200);
    frame.setVisible(true);

  }
}

3).

import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.awt.*;

public class InputMapComponents{
  JFrame frame;
  JPanel panel;
  JLabel label;
  JTextArea area;
  JScrollPane pane;
  InputMap map;
  //ActionMap map;
  public static void main(String[] args) {
  InputMapComponents m = new InputMapComponents();
  }
  public InputMapComponents(){
  frame = new JFrame(" Adding an InputMap to a Component");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  panel = new JPanel();  
  area = new JTextArea(7,10);
  pane = new JScrollPane(area);
  map = area.getInputMap();
  System.out.println(map);
  //map = area.getActionMap();
  KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.cutAction);
  //map.put(key, action)
  key = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.copyAction);
  key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.pasteAction);
  key = KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.backwardAction);
  key = KeyStroke.getKeyStroke(KeyEvent.VK_R, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.forwardAction);
  key = KeyStroke.getKeyStroke(KeyEvent.VK_U, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.upAction);
  key = KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK);
  map.put(key, DefaultEditorKit.downAction);
  String lbl = "<html><b>" + "Ctrl+p = paste" 
+ "<br>" + "Ctrl+y = copy" + 
"<br>" + "Ctrl+c = cut" + "<br>"
 + "Ctrl+l = cursor shift left one character" 
+ "<br>" + "Ctrl+r = cursor shift right one character" + "<br>"
 + "Ctrl+u = cursor shift up one line" + "<br>" 
+ "Ctrl+d = cursor shift down one line" + "</b></html>";
  JLabel label = new JLabel(lbl);
  panel.add(pane);
  panel.add(label);
  frame.add(panel);
  frame.setSize(400,200);
  frame.setVisible(true);
  
  }
}




  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Java Swing的`JMenuItem`上设置快捷键并触发事件,您可以使用`KeyStroke`和`Action`类的组合。下面是一个示例代码: ```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class JMenuItemShortcutExample { public static void main(String[] args) { JFrame frame = new JFrame("JMenuItem Shortcut Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem openMenuItem = new JMenuItem("Open"); openMenuItem.addActionListener((ActionEvent e) -> { // 在这里添加您想要执行的打开文件操作 System.out.println("执行打开文件操作"); }); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK); // 设置快捷键为Ctrl + O openMenuItem.setAccelerator(keyStroke); fileMenu.add(openMenuItem); menuBar.add(fileMenu); frame.setJMenuBar(menuBar); frame.setSize(300, 200); frame.setVisible(true); } } ``` 在上述示例中,我们创建了一个简单的Java Swing应用程序窗口,并在菜单栏中添加了一个"File"菜单。然后,我们创建了一个"Open"菜单项,并使用`setAccelerator()`方法将快捷键设置为Ctrl + O。当用户按下Ctrl + O组合键时,将执行添加的操作,此处我们仅简单地打印一条消息。 请注意,`InputEvent.CTRL_DOWN_MASK`用于指定Ctrl键的修饰符。根据需要,您可以使用其他修饰符,如`InputEvent.SHIFT_DOWN_MASK`、`InputEvent.ALT_DOWN_MASK`等。 这是一个简单的示例,您可以根据您的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值