0

当用户键入特定字符时,我试图触发一个弹出菜单。在我的情况下,它是点键。但没有任何反应。我认为;我错过了一些东西。你能告诉我出了什么问题吗?因为我完全糊涂了

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);    
    }
};
4

1 回答 1

1

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

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

以便KeyStrokeJTextArea 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

于 2013-07-19T18:20:06.787 回答