20-CS-694 Advanced Programming Techniques Spring 2012
Menus

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous      Next      Applet Source      All lectures

JMenu Test

Make menu choices in the usual way

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

class MyFrame extends JFrame implements ActionListener, ItemListener {
   JLabel l;
   JMenuItem red, green, blue, small, med, large, out;
   JCheckBoxMenuItem rev;
   Container cp;

   public MyFrame() {
      JMenuBar mb = new JMenuBar();
      JMenu m = new JMenu("Colors");
      m.add(red = new JMenuItem("Red"));
      m.add(blue = new JMenuItem("Blue"));
      m.add(green = new JMenuItem("Green"));
      red.addActionListener(this);
      blue.addActionListener(this);
      green.addActionListener(this);      
      m.add(new JMenuItem("-"));
      m.add(rev = new JCheckBoxMenuItem("Reverse Text"));
      rev.addItemListener(this);
      m.add(new JMenuItem("-"));
      m.add(out = new JMenuItem("Hide"));
      out.addActionListener(this);
      mb.add(m);
      JMenu p = new JMenu("Text Size");
      p.add(small = new JMenuItem("Small"));
      small.addActionListener(this);
      p.add(med = new JMenuItem("Medium"));
      med.addActionListener(this);
      p.add(large = new JMenuItem("Large"));
      large.addActionListener(this);
      mb.add(p);
      setJMenuBar(mb);

      cp = getContentPane();
      cp.setLayout(new GridLayout(1,1));

      l = new JLabel("This is a Menu Test", JLabel.CENTER);
      l.setForeground(Color.white);
      cp.add(l);
   }

   public void itemStateChanged (ItemEvent evt) {
      if (evt.getSource() == rev) {
         if (l.getForeground() == Color.black)
            l.setForeground(Color.white);
         else
            l.setForeground(Color.black);
      }
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == red) cp.setBackground(Color.red);
      else if (evt.getSource() == blue) cp.setBackground(Color.blue);
      else if (evt.getSource() == green) cp.setBackground(Color.green);   
      else if (evt.getSource() == out) hide();
      else if (evt.getSource() == small)
         l.setFont(new Font("TimesRoman", Font.PLAIN, 10));
      else if (evt.getSource() == med)
         l.setFont(new Font("TimesRoman", Font.PLAIN, 18));
      else if (evt.getSource() == large)
         l.setFont(new Font("TimesRoman", Font.PLAIN, 28));
   }
}

public class MenuTestApplet extends Applet {
   public void init () {
      MyFrame window = new MyFrame();
      window.setSize(300,200);
      window.setVisible(true);
   }
}