import Java.awt.*;
import Java.awt.event.*;
import Javax.swing.*;
//左鍵彈出菜單
public class JPopMenuDemo extends JFrame {
JRadioButtonMenuItem items[]; //菜單項
Color[] colors={Color.blue,Color.pink,Color.yellow,Color.red,Color.orange}; //顏色數組
JPopupMenu popupMenu; //彈出菜單
public JPopMenuDemo()
{
super( "右鍵彈出菜單" ); //調用父類構造函數
ChangeColorAction action = new ChangeColorAction(); //菜單項事件處理
String[] str = {"Blue","Pink","Yellow","Red","Orange"}; //菜單項名稱
ButtonGroup colorGroup=new ButtonGroup(); //實例化按鈕組
popupMenu=new JPopupMenu(); //實例化彈出菜單
items=new JRadioButtonMenuItem[5]; //初始化數組
for (int i=0;i items[i]=new JRadioButtonMenuItem(str[i]); //實例化菜單項
popupMenu.add(items[i]); //增加菜單項到菜單上
colorGroup.add(items[i]); //增加菜單項到按鈕組
items[i].addActionListener(action); //菜單項事件處理
}
addMouseListener(new MouseAdapter(){ //窗口的鼠標事件處理
public void mousePressed( MouseEvent event ) { //點擊鼠標
triggerEvent(event); //調用triggerEvent方法處理事件
}
public void mouseReleased( MouseEvent event ) { //釋放鼠標
triggerEvent(event);
}
private void triggerEvent(MouseEvent event) { //處理事件
if (event.isPopupTrigger()) //如果是彈出菜單事件(根據平台不同可能不同)
popupMenu.show(event.getComponent(),event.getX(),event.getY()); //顯示菜單
}
});
getContentPane().setBackground(Color.white); //窗口的默認背景色為白色
setSize(230,160); //設置窗口大小
setVisible(true); //設置窗口為可視
setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE ); //關閉窗口時退出程序
}
class ChangeColorAction implements ActionListener { //菜單項事件處理
public void actionPerformed(ActionEvent event) {
for (int i=0;i if (event.getSource()==items[i]) { //判斷事件來自於哪個菜單項
getContentPane().setBackground(colors[i]); //設置窗口背景
repaint(); //重繪窗口
return;
}
}
}
public static void main( String args[]) {
new JPopMenuDemo();
}
}
運行結果: