下面的示例展示了如何在Java Swing应用程序中显示弹出菜单。
使用以下API -
JPopupMenu - 创建弹出菜单。
JMenuItem - 创建菜单项。
示例
package com.yiibai.swingdemo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class SwingTester {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingTester() {
prepareGUI();
}
public static void main(String[] args) {
SwingTester swingMenuDemo = new SwingTester();
swingMenuDemo.showPopupMenuDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("Java SWING创建弹出菜单项");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showPopupMenuDemo() {
final JPopupMenu editMenu = new JPopupMenu("Edit");
JMenuItem cutMenuItem = new JMenuItem("剪切");
cutMenuItem.setActionCommand("Cut");
JMenuItem copyMenuItem = new JMenuItem("复制");
copyMenuItem.setActionCommand("Copy");
JMenuItem pasteMenuItem = new JMenuItem("粘贴");
pasteMenuItem.setActionCommand("Paste");
MenuItemListener menuItemListener = new MenuItemListener();
cutMenuItem.addActionListener(menuItemListener);
copyMenuItem.addActionListener(menuItemListener);
pasteMenuItem.addActionListener(menuItemListener);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
mainFrame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
editMenu.show(mainFrame, e.getX(), e.getY());
}
});
mainFrame.add(editMenu);
mainFrame.setVisible(true);
}
class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText(e.getActionCommand() + " MenuItem clicked.");
}
}
}
执行上面示例代码,得到以下结果:
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。