gpt4 book ai didi

java - 弹出菜单似乎不起作用

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

当用户键入特定字符时,我试图触发弹出菜单。在我的例子中,它是点键。但没有任何反应。我想;我错过了一些事情。你能告诉我出了什么问题吗?因为我完全困惑了

public class d extends  JPanel  {
String phase="Some Clue ";
final JTextArea area;
final JPopupMenu menu;

public d(){
super(new BorderLayout());

area=new JTextArea();
area.setLineWrap(true);
JButton button=new JButton("Clear");

menu=new JPopupMenu();
JMenuItem item=new JMenuItem(phase);
menu.add(item);

add(area,BorderLayout.NORTH);
add(button,BorderLayout.SOUTH);
add(menu);
}

public static void main(String...args){
JComponent c=new d();
JFrame frame=new JFrame();
frame.setContentPane(c);
frame.setSize(300,300);
frame.setVisible(true);
}

ActionListener listener=new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
PopupMenu menu=new PopupMenu();
int pos=area.getCaretPosition();
try {
Rectangle r= area.modelToView(pos);
menu.show(area, r.x, r.y);
} catch (BadLocationException ex) {
System.out.print(ex.toString());
}
KeyStroke ks=KeyStroke.getKeyStroke(KeyEvent.VK_P,0,false);
area.registerKeyboardAction(listener, ks,JComponent.WHEN_FOCUSED);
}
};

最佳答案

将这些语句移至类的构造函数中 d

KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_P, 0, false);
area.registerKeyboardAction(listener, ks, JComponent.WHEN_FOCUSED);

以便将KeyStroke注册到JTextArea 区域

此外,无需在监听器中创建另一个 (AWT) 弹出菜单 - 重新使用在类级别声明的 menu

ActionListener listener = new ActionListener() {

@Override
public void actionPerformed(ActionEvent ae) {

int pos = area.getCaretPosition();
try {
Rectangle r = area.modelToView(pos);
menu.show(area, r.x, r.y);
} catch (BadLocationException ex) {
System.out.print(ex.toString());
}

}
};

旁白:使用 Java 命名约定类以大写字母开头,例如 PopupTest 而不是 d

关于java - 弹出菜单似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17752589/

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