import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestJPopupMenu extends JFrame implements ActionListener,MouseListener{
JMenuBar jmb;
JMenu ColorMenu;
JPopupMenu pop;
JButton b1,b2,b3,b4;
JMenuItem j1,j2,j3,j4;
Container cp=null;
JPanel p1,p2;
public TestJPopupMenu(){
super("改变背景颜色");
jmb=new JMenuBar();
setJMenuBar(jmb);
ColorMenu=new JMenu("Color");
jmb.add(ColorMenu);
j1=new JMenuItem("red");
j2=new JMenuItem("green");
j3=new JMenuItem("blue");
j4=new JMenuItem("gray");
ColorMenu.add(j1);
ColorMenu.add(j2);
ColorMenu.add(j3);
ColorMenu.add(j4);
pop=new JPopupMenu();
JMenuItem i1=new JMenuItem("red");
JMenuItem i2=new JMenuItem("green");
JMenuItem i3=new JMenuItem("blue");
JMenuItem i4=new JMenuItem("gray");
ColorMenu.add(j1);ColorMenu.addSeparator();
ColorMenu.add(j2);ColorMenu.addSeparator();
ColorMenu.add(j3);ColorMenu.addSeparator();
ColorMenu.add(j4);
pop.add(i1); pop.add(i2); pop.add(i3); pop.add(i4);
i1.addActionListener(this);
i2.addActionListener(this);
i3.addActionListener(this);
i4.addActionListener(this);
b1=new JButton("red");
b2=new JButton("green");
b3=new JButton("blue");
b4=new JButton("gray");
p1=new JPanel();p1 . setBackground(Color.CYAN);
p2=new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.CENTER,20,10));
cp=getContentPane();
p2.add(b1);p2.add(b2);p2.add(b3);p2.add(b4);
cp.add(p1,BorderLayout.CENTER);
cp.add(p2,BorderLayout.SOUTH);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
j1.addActionListener(this);
j2.addActionListener(this);
j3.addActionListener(this);
j4.addActionListener(this);
cp.addMouseListener(this);
setSize(200,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
p1.setBackground(Color.red);
if(e.getSource()==b2)
p1.setBackground(Color.green);
if(e.getSource()==b3)
p1.setBackground(Color.blue);
if(e.getSource()==b4)
p1.setBackground(Color.gray);
String m=e.getActionCommand();
if(m=="red")
p1.setBackground(Color.red);
if(m=="green")
p1.setBackground(Color.green);
if(m=="blue")
p1.setBackground(Color.blue);
if(m=="gray")
p1.setBackground(Color.gray);
}
public void mouseReleased(MouseEvent e){
if (e.isPopupTrigger())
pop.show((Component)e.getSource(),e.getX(),e.getY());
}
public void mousePressed(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public static void main(String args[]){
TestJPopupMenu frame = new TestJPopupMenu ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}