我想知道在关注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);
}
});
}
}
答案 0 :(得分:1)
我不太确定他们为什么会这样做,但你必须使用JPopupMenu.addMenuKeyListener()
。
当我测试这个时,事件被传递了两次,所以我必须存储从event.getWhen()
获得的最后一个事件的时间,并且只处理比上次存储时间更新的事件。
答案 1 :(得分:0)
是的,可以使用registerKeyboardAction
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
jpopMenu.registerKeyboardAction(actionListener, keystroke, JComponent.WHEN_FOCUSED);
JComponent.WHEN_FOCUSED
将允许您在JPopMenu
聚焦时从键盘输入检测。