Java Reference
In-Depth Information
We will be adding functionality to this example over several chapters, so create a directory for it with
the name
Sketcher
. This program will be a window-based sketching program that will enable you to
create sketches using lines, circles, curves, and rectangles, and to annotate them with text. By building
an example in this way, you will gradually create a much larger Java program than the examples seen so
far, and you will also gain experience of combining many of the capabilities of
javax.swing
and
other standard packages in a practical situation.
Try It Out - Building a Menu
To start with, we will have two class files in the Sketcher program. The file
Sketcher.java
will
contain the method
main()
where execution of the application will start, and the file
SketchFrame.java
will contain the class defining the application window.
We will define a preliminary version of our window class as:
// Frame for the Sketcher application
import javax.swing.*;
public class SketchFrame extends JFrame {
// Constructor
public SketchFrame(String title) {
setTitle(title); // Set the window title
setDefaultCloseOperation(EXIT
_
ON
_
CLOSE);
setJMenuBar(menuBar); // Add the menu bar to the window
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
}
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
}
After you have entered this code into a new file, save the file in the
Sketcher
directory as
SketchFrame.java
.
Next, you can enter the code for the
Sketcher
class in a separate file:
// Sketching application
import java.awt.Toolkit;
import java.awt.Dimension;
public class Sketcher {
static SketchFrame window; // The application window
public static void main(String[] args) {
window = new SketchFrame("Sketcher"); // Create the app window
Toolkit theKit = window.getToolkit(); // Get the window toolkit