我试图在用户输入特定字符时触发弹出菜单。在我的情况下,这是点密钥。但没有任何反应。我认为;我错过了什么。你能告诉我出了什么问题。因为我完全糊涂了
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);
}
};
答案 0 :(得分:1)
将这些语句移到类d
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_P, 0, false);
area.registerKeyboardAction(listener, ks, JComponent.WHEN_FOCUSED);
以便KeyStroke
注册JTextArea
area
此外,无需在侦听器中创建另一个(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