Java Reference
In-Depth Information
If you create a JCheckboxMenuItem object by passing just a String argument to the constructor, the
object represents a checkbox menu item that is initially unchecked. For example, you could create an un-
checked item with the following statement:
JCheckboxMenuItem circleItem = new JCheckboxMenuItem("Circle");
Another constructor for this class enables you to set the check mark by specifying a second argument of
type boolean . For example:
JCheckboxMenuItem lineItem = new JCheckboxMenuItem("Line", true);
This creates an item with the label, Line , which is checked initially. You can, of course, also specify that
you want an item to be unchecked by setting the second argument to false .
A JRadioButtonMenuItem object is created in essentially the same way:
JRadioButtonMenuItem item = new JRadioButtonMenuItem("Curve", true);
This creates a radio button menu item that is selected.
If you want to use a menu bar in your application window, you must create your window as a JFrame
object because the JFrame class incorporates the capability to manage a menu bar. You can also add a menu
bar to JDialog and JApplet objects. Let's explore how you create a menu on a menu bar.
Creating a Menu
To create a window with a menu bar, you need to define your own window class as a subclass of JFrame .
This provides a much more convenient way to manage all the details of the window compared to using a
JFrame object directly. By extending the JFrame class, you can add your own members that customize a
JFrame window to your particular needs. You can also override the methods defined in the JFrame class to
modify their behavior, if necessary.
You add functionality to this example over several chapters, so create a directory for it with the name
Sketcher. You develop this program into a window-based sketching program that enables you to create
sketches using lines, circles, curves, and rectangles, and to annotate them with text. By building an example
in this way, you gradually create a much larger Java program than the examples seen so far, and you also
gain experience in combining many of the capabilities of javax.swing and other standard packages in a
practical situation. Note that this is not a smooth progression. From time to time you might backtrack on
function in Sketcher to implement it better. The final version ends up combining the major techniques you
have learned for implementing an interactive application in Java.
TRY IT OUT: Building a Menu
To start with, you have two class files in the Sketcher program. The file Sketcher.java contains the
main() method where execution of the application starts, and the SketcherFrame.java file contains the
class defining the application window.
You can define a preliminary version of the window class as follows:
Search WWH ::




Custom Search