Java中JButton的击键/热键

Java中JButton的击键/热键,java,swing,jbutton,hotkeys,jmenu,Java,Swing,Jbutton,Hotkeys,Jmenu,最初,我使用JMenu并使用加速器建立热键。它工作得很好。现在我想在JButton中有同样的行为,但我被卡住了。 下面是我写的代码:请分享你的想法,这样我才能走上正确的道路 import javax.swing.*; import java.awt.Event; import java.awt.event.*; import java.util.Arrays; public class ShowDialogBox{ JFrame frame; public static vo

最初,我使用JMenu并使用加速器建立热键。它工作得很好。现在我想在JButton中有同样的行为,但我被卡住了。 下面是我写的代码:请分享你的想法,这样我才能走上正确的道路

import javax.swing.*;

import java.awt.Event;
import java.awt.event.*;
import java.util.Arrays;

public class ShowDialogBox{
    JFrame frame;
    public static void main(String[] args){
        ShowDialogBox db = new ShowDialogBox();
    }

    public ShowDialogBox(){
        frame = new JFrame("Show Message Dialog");
        // create an Action doing what you want
        KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK); 
        Action performSave = new AbstractAction("Click Me") {  
            public void actionPerformed(ActionEvent e) {     
                 //do your save
                 System.out.println("clickMe");
            }
        }; 


        JButton button = new JButton("Click Me");


        button.getActionMap().put("Click Me", performSave);
        button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "Click Me");

        button.addActionListener(new MyAction());
        frame.add(button);
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public class MyAction implements ActionListener{
        public void actionPerformed(ActionEvent e){



            String[] items = {
                    "1", "2", "3"
                };
                JList list = new JList(items);
                JPanel panel = new JPanel();
                panel.add(list);
                JOptionPane.showMessageDialog(null, panel);

        }

提前感谢

要使键绑定正常工作,请使用
KeyEvent.CTRL\u DOWN\u掩码
而不是
KeyEvent.CTRL\u掩码

我自己更喜欢使用AbstractActions而不是ActionListeners,因为这样菜单和按钮可以共享相同的动作,并且动作可以有自己的助记符键,尽管这需要一个alt键组合。例如:

import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class ShowMyDialogTest {

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Show MyDialog Test");

      JPanel mainPanel = new JPanel();
      Action showAction = new ShowDialogAction(frame, "Show Dialog");
      final JButton showDialogBtn = new JButton(showAction);
      mainPanel.add(showDialogBtn);
      mainPanel.setPreferredSize(new Dimension(600, 400));

      KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK);
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = showDialogBtn.getInputMap(condition);
      ActionMap actionMap = showDialogBtn.getActionMap();
      inputMap.put(keyStroke, keyStroke.toString());
      actionMap.put(keyStroke.toString(), new AbstractAction() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            showDialogBtn.doClick();
         }
      });

      JMenuItem showMenuItem = new JMenuItem(showAction);
      JMenuItem exitMenuItem = new JMenuItem(new DisposeAction("Exit", KeyEvent.VK_X));
      JMenu fileMenu = new JMenu("File"); 
      fileMenu.setMnemonic(KeyEvent.VK_F);
      fileMenu.add(showMenuItem);
      fileMenu.add(exitMenuItem);

      JMenuBar menuBar = new JMenuBar();
      menuBar.add(fileMenu);
      frame.setJMenuBar(menuBar);      

      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class ShowDialogAction extends AbstractAction {
   private JFrame frame;
   private ShowDialogPanel dialogPanel;
   private JDialog dialog;

   public ShowDialogAction(JFrame frame, String name) {
      super(name);
      int mnemonic = (int) name.charAt(0);
      putValue(MNEMONIC_KEY, mnemonic);
      this.frame = frame;
   }

   @Override
   public void actionPerformed(ActionEvent e) {
      if (dialogPanel == null) {
         dialogPanel = new ShowDialogPanel();
      }
      if (dialog == null) {
         dialog = new JDialog(frame, "My Dialog", ModalityType.APPLICATION_MODAL);
         dialog.getContentPane().add(dialogPanel);
         dialog.pack();
      }
      dialog.setLocationRelativeTo(frame);
      dialog.setVisible(true);
      // TODO add any code that extracts data from dialogPanel

   }
}

class ShowDialogPanel extends JPanel {
   private JButton button = new JButton(new DisposeAction("Close", KeyEvent.VK_C));

   public ShowDialogPanel() {
      add(button);
   }
}

class DisposeAction extends AbstractAction {
   private static final long serialVersionUID = 1L;

   public DisposeAction(String name, int mnemonic) {
      super(name);
      putValue(MNEMONIC_KEY, mnemonic);
   }

   @Override
   public void actionPerformed(ActionEvent e) {
      Component component = (Component) e.getSource();
      Window win = SwingUtilities.getWindowAncestor(component);
      if (win == null) {
         JPopupMenu popup = (JPopupMenu) component.getParent();
         if (popup == null) {
            return;
         }
         component = popup.getInvoker();
         win = SwingUtilities.getWindowAncestor(component);
      }
      win.dispose();
   }
}

热键通常使用alt键组合来完成,通过使用AbstractAction、调用
setAction(…)
并为操作提供适当的助记符,JButtons和JMenuItems都可以轻松完成。是否确实要执行控制键组合?如果是这样,请使用
KeyEvent.CTRL\u DOWN\u掩码
而不是
KeyEvent.CTRL\u掩码
。谢谢@气垫船