gpt4 book ai didi

java - 关注 JpopupMenu 时检测键盘输入 (Java)

转载 作者:行者123 更新时间:2023-12-01 14:36:31 25 4
gpt4 key购买 nike

我想知道是否有任何方法可以在关注 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);
}
});
}

}

最佳答案

我不太清楚他们为什么这样做,但你必须使用JPopupMenu.addMenuKeyListener()

当我对此进行测试时,事件被传递了两次,因此我必须存储从 event.getWhen() 获取的最后一个事件的时间,并且只处理比上次存储时间更新的事件.

关于java - 关注 JpopupMenu 时检测键盘输入 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com