import javax.swing.* ; import java.awt.* ; import java.awt.event.* ; class MenuFrame extends JFrame implements ActionListener { public MenuFrame() { addWindowListener(new TerminationListener()) ; setTitle("MenuFrame") ; setSize(450, 300) ; JMenuBar menuBar = new JMenuBar() ; setJMenuBar(menuBar) ; JMenu fileMenu = new JMenu("File") ; menuBar.add(fileMenu) ; closeItem = new JMenuItem("Exit") ; closeItem.addActionListener(this) ; fileMenu.add(closeItem) ; JMenu viewMenu = new JMenu("View") ; menuBar.add(viewMenu) ; redItem = new JMenuItem("Red") ; redItem.addActionListener(this) ; viewMenu.add(redItem) ; blueItem = new JMenuItem("Blue") ; blueItem.addActionListener(this) ; viewMenu.add(blueItem) ; } public void actionPerformed(ActionEvent evt) { if(evt.getSource() == closeItem) System.exit(0) ; else if(evt.getSource() == redItem) getContentPane().setBackground(Color.red) ; else if(evt.getSource() == blueItem) getContentPane().setBackground(Color.blue) ; } private JMenuItem closeItem, redItem, blueItem ; } public class MenuTest { public static void main(String [] args) { JFrame frame = new MenuFrame() ; frame.show() ; } } class TerminationListener implements WindowListener { public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0) ; } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }