Java Reference
In-Depth Information
Swing includes the concept of .a “layout.” A layout. is an object that defines the relationship
between other objects. For example, if you use a BoxLayout object, your components go in a line either
horizontally or vertically. A grid layout, on the other hand, creates a layout that looks like a table (a
number of cells wide by a number of cells high). Java also has a number of other layouts. We use a
number of them in this chapter and later in the topic. One handy thing about layouts is that you can use
layouts within layouts. For example, you might use a BoxLayout object set to vertical and then use a
number of other BoxLayouts, each set to horizontal, to add rows of components to your window. You
can achieve a similar effect with a GridLayout object, too, but the BoxLayout with BoxLayout scheme
might work better if you have different numbers of objects to put in each row.
I can go on for a long time (probably for a whole book) about all the options available in Swing, but
I'll mention just one more that may be of interest to you. Swing includes different looks for programs. If
you use the default settings (as I do in this chapter), you get Java's Metal look, which is meant to look the
same on all operating systems. To get the native layout for any given operating system, use the
SystemLookAndFeel object. If you use SystemLookAndFeel , people who use your software on Windows get
a Windows look and feel, whereas users on other operating systems get the look and feel of those
operating systems. The down side is that if Java can't figure out the look and feel of the system, your
program doesn't work. That's why so many Java programs (especially those written for demonstrations
and topics) use the default (Metal) look and feel. Still, if you're writing software just for yourself or for a
group of users who use the same operating system, and you can be sure that Java supports that
operating system's look and feel, you can make your programs look just like the other programs that run
on that operating system.
Now, let's do a little more with our program. Let's start by adding a feature many programs have, a
menu. Listing 7.2 shows how to add .a menu.
Listing 7-2. A Swing program with a menu
package com.apress.java7forabsolutebeginners.examples.swingdemo;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo implements ActionListener {
private JFrame frame = new JFrame("SwingDemo");
private void addMenu(JFrame frame) {
JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
exitItem.addActionListener(this);
file.add(exitItem);
JMenuBar menuBar = new JMenuBar();
Search WWH ::




Custom Search