JPopupMenu組件類似於window桌面點擊右鍵的效果,在點擊處彈出一個動態菜單。
代碼:
package org.suju.swingdemo;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
public class JPopupMenuDemo {
/*
* frame 窗體
* pop 彈出菜單項
* more 子菜單想
* opentiem, helpitem 子菜單選項
*/
public JFrame frame;
public JPopupMenu pop;
public JMenu more;
public MyMenuItem openitem;
public MyMenuItem helpitem;
//init
public void init()
{
//通過數組構造菜單項,如果菜單項很多
MyMenuItem[] items = new MyMenuItem[]{
new MyMenuItem("File", new ImageIcon("img/new_page.png")),
new MyMenuItem("Print", new ImageIcon("img/print.png")),
new MyMenuItem("Exit", new ImageIcon("img/save.png")),
};
openitem = new MyMenuItem("Exit", new ImageIcon("img/open.png"));
helpitem = new MyMenuItem("Exit", new ImageIcon("img/help.png"));
//創建pop彈出式菜單,並添加所有菜單項
pop = new JPopupMenu("pop");
more = new JMenu("more");
more.add(openitem);
more.add(helpitem);
for (MyMenuItem item: items) {
pop.add(item); //遍歷添加數組菜單項
}
pop.addSeparator(); //分隔符
pop.add(more);
frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setTitle("JPopupMenuDemo");
frame.setBounds(500, 100, 300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(new MouseAdapter() {
/*
* MouseEvent.BUTTON3 代表按下鼠標右鍵
* pop.show(frame, e.getX(), e.getY());
* 在frame響應鼠標點擊出,彈出菜單
*/
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
pop.show(frame, e.getX(), e.getY());
}
}
});
}
public void show()
{
init();
frame.setVisible(true);
}
public static void main(String[] args) {
new JPopupMenuDemo().show();
}
/*
* 僅方便簡化測試
* 自定一個菜單項類,繼承ActionListener響應點擊事件
*/
class MyMenuItem extends JMenuItem implements ActionListener
{
private static final long serialVersionUID = 1L;
public MyMenuItem(String string, ImageIcon imageIcon) {
super(string, imageIcon);
this.addActionListener(this);
}
//點擊響應方法
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, e.getActionCommand());
}
}
}
源碼:下載