本文概述
- JPopupMenu类声明
- Java JPopupMenu示例
- 带有MouseListener和ActionListener的Java JPopupMenu示例
JPopupMenu类声明 【Java JPopupMenu】我们来看一下javax.swing.JPopupMenu类的声明。
public class JPopupMenu extends JComponent implements Accessible, MenuElement
常用的构造函数:
建设者 | 描述 |
---|---|
JPopupMenu() | 构造一个不带“调用程序”的JPopupMenu。 |
JPopupMenu(String label) | 构造具有指定标题的JPopupMenu。 |
import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final JFrame f= new JFrame("PopupMenu Example");
final JPopupMenu popupmenu = new JPopupMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}}
输出:
文章图片
带有MouseListener和ActionListener的Java JPopupMenu示例
import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final JFrame f= new JFrame("PopupMenu Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400, 100);
final JPopupMenu popupmenu = new JPopupMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
cut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setText("cut MenuItem clicked.");
}
});
copy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setText("copy MenuItem clicked.");
}
});
paste.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setText("paste MenuItem clicked.");
}
});
f.add(label);
f.add(popupmenu);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}
}
输出:
文章图片
推荐阅读
- Windows 10无法删除打印机设备(这是修复方法和教程!)
- Java JOptionPane
- Java JPasswordField用法
- Java JPanel
- Java JDialog
- Java JMenuBar,JMenu和JMenuItem
- Java JList用法
- Java JLayeredPane
- Java JLabel用法