// Scott DeRuiter 4/28/03 // MenuShape.java // Illustrates Menus import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MenuShape extends JApplet { private JMenuItem Blue, Red, Gray; private JMenuItem Circle, Square; private JMenuItem Fill, Draw; private int colorchoice = 1; private boolean shapechoice = true; private boolean fillchoice = true; public MenuShape ( ) { setBackground(Color.gray); MyCanvas canvas = new MyCanvas(); setContentPane(canvas); JMenuBar menuBar = new JMenuBar ( ); setJMenuBar(menuBar); JMenu ColorMenu = new JMenu ( "SHAPE COLORS" ); Blue = new JMenuItem ( "BLUE" ); ColorMenu.add ( Blue ); Blue.addActionListener ( canvas ); ColorMenu.addSeparator ( ); Red = new JMenuItem ( "RED" ); ColorMenu.add ( Red ); Red.addActionListener ( canvas ); ColorMenu.addSeparator ( ); Gray = new JMenuItem ( "GRAY" ); ColorMenu.add ( Gray ); Gray.addActionListener ( canvas ); menuBar.add ( ColorMenu ); JMenu ShapeMenu = new JMenu ( "SHAPES" ); Circle = new JMenuItem ( "CIRCLE" ); ShapeMenu.add ( Circle ); Circle.addActionListener ( canvas ); ShapeMenu.addSeparator ( ); Square = new JMenuItem ( "SQUARE" ); ShapeMenu.add ( Square ); Square.addActionListener ( canvas ); menuBar.add ( ShapeMenu ); JMenu TypeMenu = new JMenu ( "FILL OR CLEAR" ); Fill = new JMenuItem ( "FILL" ); TypeMenu.add ( Fill ); Fill.addActionListener ( canvas ); TypeMenu.addSeparator ( ); Draw = new JMenuItem ( "CLEAR" ); TypeMenu.add ( Draw ); Draw.addActionListener ( canvas ); menuBar.add ( TypeMenu ); } public Insets getInsets() { return new Insets(3,3,3,3); } class MyCanvas extends JPanel implements ActionListener { public void paintComponent (Graphics g) { super.paintComponent ( g ); if ( colorchoice == 1 ) g.setColor ( Color.blue ); else if ( colorchoice == 2 ) g.setColor ( Color.red ); else if ( colorchoice == 3 ) g.setColor ( Color.gray ); if ( shapechoice && fillchoice ) g.fillRect ( 80, 80, 320, 320 ); else if ( !shapechoice && fillchoice ) g.fillOval ( 80, 80, 320, 320 ); else if ( shapechoice && !fillchoice ) g.drawRect ( 80, 80, 320, 320 ); else if ( !shapechoice && !fillchoice ) g.drawOval ( 80, 80, 320, 320 ); } public void actionPerformed ( ActionEvent e ) { if ( e.getSource ( ) == Blue ) colorchoice = 1; else if ( e.getSource ( ) == Red ) colorchoice = 2; else if ( e.getSource ( ) == Gray ) colorchoice = 3; else if ( e.getSource ( ) == Square ) shapechoice = true; else if ( e.getSource ( ) == Circle ) shapechoice = false; else if ( e.getSource ( ) == Fill ) fillchoice = true; else if ( e.getSource ( ) == Draw ) fillchoice = false; repaint ( ); } } }