在Java中右键单击JTextArea时显示JPopupMenu?

时间:2011-12-30 21:46:13

标签: java swing jtextarea jpopupmenu

我正在创建一个简单的便利贴应用程序。我想点击JPopupMenu时显示JTextArea。因为它是一个粘滞便笺,所以很明显整个应用程序都是textArea

短代码:

    //I've tried my best to follow SSCE

private JTextArea textArea = new JTextArea();
private JPopupMenu popup = new JPopupMenu("Popup Menu");
private JMenuItem hideBar = new JMenuItem("Hide Bar");
private JMenuItem hideTitle = new JMenuItem("Hide Item");

public mySticky(){

add(textArea); //Text Area is using the whole Frame "Sticky Note"
popup.add(hideBar);  //adding MenuItem
popup.add(hideTitle); //adding MenuItem
//addMouseListener(new popupTriggerListener());
textArea.addMouseListener(new popupTriggerListener());

}


private class popupTriggerListener extends MouseAdapter{
    public void MousePressed(MouseEvent e){
        if(e.isPopupTrigger())
            popup.show(textArea,e.getX(),e.getY()); //I've added texArea I'm not sure what to add inside.
    }

    public void MouseReleased(MouseEvent e){
        if(e.isPopupTrigger())
            popup.show(textArea,e.getX(),e.getY()); //I've added texArea I'm not sure what to add inside.
    }

    public void MouseClicked(MouseEvent e){

    }
}

1 个答案:

答案 0 :(得分:3)

  

我已尽力遵循SSCE

如果代码甚至无法编译,那怎么可能是SSCCE?请尝试再次阅读该链接。

我建议您首先阅读Bringing Up a Popup Menu上Swing教程中的部分,以获取一个工作示例。

  

嗯,我在这里错过了什么

当您覆盖方法时,您缺少应在方法签名之前的@Override语句。这样可以防止您输入错误。