Java Reference
In-Depth Information
public
MyFrame ( )
{
...
JMenuBar bar =
new
JMenuBar ( ) ;
setJMenuBar(bar ) ;
JMenu color =
new
JMenu(
"Color"
);
bar .add( color ) ;
JMenuItem green =
new
JMenuItem(
"Green"
);
JMenuItem red =
new
JMenuItem(
"Red"
);
JMenuItem blue =
new
JMenuItem(
"Blue"
);
color .add(green) ;
color .add(red);
color .add(blue) ;
}
}
Since the menu is part of Swing, we need to use
J
in front of all the class names. Note
that since a window can have at most one
JMenuBar
, we need to use the
setJMenuBar
method to add the menu bar to the window. Every menu and menu item has a name, which
is specified in the constructor of the class. The menus are added to the menu bar and the
menu items are added to the menus.
The life of a menu item is relatively simple. The only thing that can happen is that it
is pressed. Therefore, it only needs to notify the
actionPerformed
method that belongs to
the interface
ActionListener
. We will add a variable
color
to the
MyPanel
class. Since
the variable will be private, we will also add a setter method for it. We will then add action
listeners to the three menu items that simply call this setter method in order to change the
drawing color for the panel. Here is the rewritten code.
import
java .awt .
∗
;
import
java .awt. event .
∗
;
import
java .awt.geom.
∗
;
import
java . util .
∗
;
import
javax . swing .
∗
;
public class
DrawingGame
{
public static void
main(String [] args)
{
MyFrame f =
new
MyFrame ( ) ;
f . setVisible(
true
);
}
}
class
MyFrame
extends
JFrame
{
MyPanel p ;
public
MyFrame ( )
{
setSize (300 , 300) ;
p=
new
MyPanel () ;
add(p) ;
JMenuBar bar =
new
JMenuBar ( ) ;
setJMenuBar(bar ) ;
JMenu color =
new
JMenu(
"Color"
);
bar .add( color ) ;
JMenuItem green =
new
JMenuItem(
"Green"
);
JMenuItem red =
new
JMenuItem(
"Red"
);
JMenuItem blue =
new
JMenuItem(
"Blue"
);
color .add(green) ;
color .add(red);
color .add(blue) ;