Question

I am trying to trigger a popup menu when user type a specific character .In my case It's dot key.But nothing happens.I think; I missed out something . Could you tell me what is wrong.Because I am completly confused

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);    
    }
};
Was it helpful?

Solution

Move these statements into the constructor of your class d

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

so that the KeyStroke is registered with the JTextArea area

Also there's no need to create another (AWT) popup menu in the listener - re-use menu declared at class level.

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

    }
};

Aside: Using Java Naming Conventions classes start with an uppercase letter, for example PopupTest rather than d

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top