Download: jar file
JPopupMenu
JMenuItem
PopupTest.java
01: // PopupTest.java 02: // Demonstrating JPopupMenus 03: import javax.swing.*; 04: import java.awt.event.*; 05: import java.awt.*; 06: 07: class TestPanel extends JPanel { 08: private JRadioButtonMenuItem items[]; 09: private Color colorValues[] = 10: { Color.blue, Color.yellow, Color.red }; 11: 12: public TestPanel() 13: { 14: 15: final JPopupMenu popupMenu = new JPopupMenu(); 16: ItemHandler handler = new ItemHandler(); 17: String colors[] = { "Blue", "Yellow", "Red" }; 18: ButtonGroup colorGroup = new ButtonGroup(); 19: items = new JRadioButtonMenuItem[ 3 ]; 20: 21: // construct each menu item and add to popup menu; also 22: // enable event handling for each menu item 23: for ( int i = 0; i < items.length; i++ ) { 24: items[ i ] = new JRadioButtonMenuItem( colors[ i ] ); 25: popupMenu.add( items[ i ] ); 26: colorGroup.add( items[ i ] ); 27: items[ i ].addActionListener( handler ); 28: } 29: 30: setBackground( Color.white ); 31: 32: // define a MouseListener for the window that displays 33: // a JPopupMenu when the popup trigger event occurs 34: addMouseListener( 35: new MouseAdapter() { 36: public void mousePressed( MouseEvent e ) 37: { checkForTriggerEvent( e ); } 38: 39: public void mouseReleased( MouseEvent e ) 40: { checkForTriggerEvent( e ); } 41: 42: private void checkForTriggerEvent( MouseEvent e ) 43: { 44: if ( e.isPopupTrigger() ) 45: popupMenu.show( e.getComponent(), 46: e.getX(), e.getY() ); 47: } 48: } 49: ); 50: } 51: 52: private class ItemHandler implements ActionListener { 53: public void actionPerformed( ActionEvent e ) 54: { 55: // determine which menu item was selected 56: for ( int i = 0; i < items.length; i++ ) 57: if ( e.getSource() == items[ i ] ) { 58: setBackground( 59: colorValues[ i ] ); 60: repaint(); 61: return; 62: } 63: } 64: } 65: } 66: 67: public class PopupTest extends JApplet 68: { 69: TestPanel panel; 70: public void init() 71: { 72: panel = new TestPanel(); 73: getContentPane().add(panel); 74: } 75: 76: public static void main( String args[] ) 77: { 78: TestPanel panel = new TestPanel(); 79: JFrame frame = new JFrame("Using JPopupMenus" ); 80: frame.add(panel); 81: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 82: frame.setSize( 300, 200 ); 83: frame.setVisible(true); 84: } 85: }
Maintained by John Loomis, updated Fri Mar 28 14:33:16 2008