用JavaSwing显示弹出菜单

用JavaSwing显示弹出菜单,java,swing,Java,Swing,我对java swing的popapMenu有问题,你能帮我吗 这是我的密码 package com.bar.menu; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPanel; import

我对java swing的popapMenu有问题,你能帮我吗 这是我的密码

package com.bar.menu;

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;

@SuppressWarnings("serial")
public class PopMenuSample extends JFrame {

public PopMenuSample() {
    super("Pop menu exemple");
    this.setSize(600, 400);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    JPanel panel = (JPanel) getContentPane();
    // the content of the window
    JScrollPane LeftjScrollPane = new JScrollPane(new JTree());
    LeftjScrollPane.setPreferredSize(new Dimension(200, 0));

    JTextArea textArea = new JTextArea();
    JScrollPane rightjScrollPane = new JScrollPane(textArea);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
    LeftjScrollPane, rightjScrollPane);
    panel.add(splitPane);

    JPopupMenu popupMenu = this.createPopupMenu();
    textArea.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent event) {
            if (event.isPopupTrigger()) {
                popupMenu.show(event.getComponent(), event.getX(), 
                  event.getY());
            }
        }
    });
}

private JPopupMenu createPopupMenu() {
    JPopupMenu popupMenu = new JPopupMenu();

    JMenuItem menuNew = new JMenuItem("New File");
    popupMenu.add(menuNew);
    return popupMenu;
}

public static void main(String[] args) throws Exception {

    UIManager.setLookAndFeel(new NimbusLookAndFeel());
    PopMenuSample menuSample = new PopMenuSample();
    menuSample.setVisible(true);

}

}
这个例子很简单(一个窗口包含两个区域,左边是Jtree(),右边是textArea,在这个地方我想激活我的问题,当我使用鼠标右键时,我想显示新文件),但我无法通过鼠标左键在textArea中显示popmenu新文件

我用的是Java8

你能帮我吗?谢谢:)

您只检查鼠标按下事件

对于不同的LAF,弹出式触发器可能不同

您还需要检查
mousererelease
事件


有关更多信息,请参阅Swing教程中的部分。

isPopupTrigger
对鼠标右键作出反应,而不是左键。我举了一个例子,他使用了public void mousePressed(MouseEvent event)@BMW83,使用Swing教程作为示例的起点。为所有Swing基础知识保留一个指向教程的链接。
public void mousePressed(MouseEvent event) {