我有这个

Action openFileChooserAction = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("actionPerformed");
                openFileChooser();
            }
        };
        KeyStroke keyStroke = KeyStroke.getKeyStroke('O', KeyEvent.CTRL_MASK);
        centerPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "openFileChooser");
        centerPanel.getActionMap().put("openFileChooser", openFileChooserAction);


如果我按ctrl然后o可以,反之亦然。当我先按o然后按ctrl时,如何使它也起作用?

最佳答案

大声笑,灵魂!猜猜您不需要扩展修饰符!我不好...

您可以使用它们,但我认为越简单越好,尤其是速度更快时!

import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SOQ18 implements KeyListener
{

   public boolean o, shift;
   public JFrame f;
   public JLabel l;

   public SOQ18()
   {

      f = new JFrame();
      l = new JLabel();
      f.setSize(200,200);
      f.setLocation(200,200);
      f.add(l);
      l.setText("Testing testing, 123...");

      f.addKeyListener(this);

      f.setVisible(true);


   }

   /** Will translate and handle the keystrokes as they are pressed and released */
   private void keyTranslate(KeyEvent e, boolean b)
   {

      int keyCode = e.getKeyCode();

      if(KeyEvent.getKeyText(keyCode).equals("O"))
      {

         o = b;

      }

      if(KeyEvent.getKeyText(keyCode).equals("Shift"))
      {

         shift = b;

      }

      if(o && shift)
      {

      //do whatever code you wanted to do here, but in the meantime...
         l.setText("They have both been pressed!");

      }

      else
      {
         l.setText("Not yet...");
      }

   }

   /** Handle the key typed event */
   public void keyTyped(KeyEvent e)
   {

      // do nothing

   }

   /** Handle the key pressed event */
   public void keyPressed(KeyEvent e)
   {

      keyTranslate(e, true);

   }

   /** Handle the key released event */
   public void keyReleased(KeyEvent e)
   {

      keyTranslate(e, false);

   }

   public static void main(String[] args)
   {

      SOQ18 soq = new SOQ18();

   }

}


如您所见,现在,您的代码尚未实现。请原谅我,因为我不知道您的代码在做什么,并且由于我没有在计算机上进行测试所需的任何文件和材料,因此我只是在上面提供了一个程序外壳。我确定您可以对其进行编辑以使其以自己的方式起作用!

现在,让我们解释发生了什么。忽略JFrameJLabel,它们只是在向您证明所有这些代码实际上都在起作用。我导入了KeyEventKeyCode,以便可以检查按下了哪个键,如在我的方法keyTranslate()中所看到的。然后,每当按下并释放键时,我就会使用接口KeyListener中的内置方法来调用keyTranslate()。最后,keyTranslate()将仅通过if语句和布尔值检查o和shift键。如果没有任何意义,请随时提问!

09-28 13:08