本文概述
PopupMenu可以在组件内的特定位置动态弹出。它继承了JComponent类。
JPopupMenu类声明
我们来看一下javax.swing.JPopupMenu类的声明。
public class JPopupMenu extends JComponent implements Accessible, MenuElement
常用的构造函数:
建设者 | 描述 |
---|---|
JPopupMenu() | 构造一个不带“调用程序”的JPopupMenu。 |
JPopupMenu(String label) | 构造具有指定标题的JPopupMenu。 |
Java 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();
}
}
输出:
评论前必须登录!
注册