在JFrame中创建快捷方式

时间:2013-05-17 07:13:13

标签: java swing jframe keylistener

public final class UserPage extends JFrame{
public UserPage() {
this.addKeyListener(new myclass());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setLocation(300, 60);
this.setResizable(false);
this.setVisible(true);
}
.
.
.
    public class myclass extends KeyAdapter{
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_DELETE) {
            System.out.println("Key \"Delete\" Pressed");
        }
    }
}
}

但是,当我按下删除按钮时,看不到“按键”删除\“按下”消息!

2 个答案:

答案 0 :(得分:5)

答案 1 :(得分:3)

  • JRootPane + KeyBindings(正如@mKorbel已经说过的那样)

    String KEY = "UserPageAction";
    f.getRootPane().getActionMap().put(KEY, action);
    InputMap im = f.getRootPane().getInputMap();
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
    
  • 同时退房:JMenuItem #setAccelerator(...)

    JMenuItem item = new JMenuItem(action);
    item.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
    

SSCCE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UserPageTest {
  public static JMenuBar makeMenuBar() {
    JMenuBar bar = new JMenuBar();
    JMenu menu = new JMenu("Test");
    JMenuItem item = new JMenuItem(action);
    item.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
    menu.add(item);
    bar.add(menu);
    return bar;
  }
  public static Action action = new AbstractAction("UserPage?") {
    @Override public void actionPerformed(ActionEvent e) {
      System.out.println("UserPage Action");
    }
  };
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() { createAndShowGUI(); }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();

    String KEY = "UserPageAction";
    f.getRootPane().getActionMap().put(KEY, action);
    InputMap im = f.getRootPane().getInputMap();
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);

    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.setJMenuBar(makeMenuBar());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}