0

我想知道是否有任何方法可以在关注 JpopupMenu 的同时检测键盘输入。这是为了在键盘检测到输入时消除对 JPopupMenu 的关注。这可能吗?

谢谢你。

下面是我编写的简化代码。

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import java.net.*; import java.io.*; public class testClass { static JPopupMenu textPopupMenu = new JPopupMenu("MENU"); final static JTextArea textInput = new JTextArea(50,80); final static JPanel overallPanel = new JPanel(); final static JFrame overallFrame = new JFrame("Test"); public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final ActionListener actionListener1 = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { textPopupMenu.setFocusable(false); } }; KeyListener textInputListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { //Get the suggested words from the function and populate them to the JMenuItem textPopupMenu = new JPopupMenu("MENU"); for(int i=0;i<5;i++) { switch(i) { case 0: JMenuItem item1 = new JMenuItem("A"); textPopupMenu.add(item1); break; case 1: JMenuItem item2 = new JMenuItem("B"); textPopupMenu.add(item2); break; case 2: JMenuItem item3 = new JMenuItem("C"); textPopupMenu.add(item3); break; case 3: JMenuItem item4 = new JMenuItem("D"); textPopupMenu.add(item4); break; case 4: JMenuItem item5 = new JMenuItem("E"); textPopupMenu.add(item5); break; }; } textPopupMenu.setFocusable(true); if (textPopupMenu.isVisible()) { textPopupMenu.setLocation(0, 0 + 20); } else { textPopupMenu.show(textInput,0, 0 + 20); } } }; textInput.addKeyListener(textInputListener); overallPanel.add(textInput); overallFrame.getContentPane().add(overallPanel); overallFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);`enter code here` overallFrame.setSize(1000, 900); overallFrame.setLocationRelativeTo(null); overallFrame.setVisible(true); } }); } }
4

2 回答 2

1

I'm not quite sure why they did this, but you have to use JPopupMenu.addMenuKeyListener().

When I tested this, events were delivered twice, so I had to store the time of the last event obtained from event.getWhen() and only process events which were newer than the last stored time.

于 2016-06-23T17:26:35.610 回答
0

是的,它可以使用 registerKeyboardAction

  KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
  jpopMenu.registerKeyboardAction(actionListener, keystroke, JComponent.WHEN_FOCUSED);

JComponent.WHEN_FOCUSEDJPopMenu将允许您在聚焦时从键盘输入检测。

于 2013-05-08T15:13:06.660 回答