用Java Swing显示PopMenu

时间:2018-07-03 13:41:59

标签: 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 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,在这个地方我想激活我的问题,而在鼠标右键上我想显示 New File ),但我无法通过鼠标左键

在textArea中显示弹出菜单 New File

我用过Java 8

能帮帮我,谢谢:)

1 个答案:

答案 0 :(得分:0)

public void mousePressed(MouseEvent event) {

您仅检查mousePressed事件。

对于不同的LAF,弹出触发器可以不同。

您还需要检查mouseReleased事件。

有关更多信息,请参见Bringing Up a Popup Menu的Swing教程中的部分。