Laying Out an Application

The layout managers you have seen thus far were applied to an entire frame; the setLayout() method of the frame was used, and all components followed the same rules. This setup can be suitable for some programs, but as you try to develop a GUI with Swing, you often find that none of the layout managers fit.

One way around this problem is to use a group of JPanel objects as containers to hold different parts of a GUI. You can set up different layout rules for each of these parts by using the setLayout() methods of each JPanel. After these panels contain all the components they need to contain, you can add the panels directly to the frame.

The next project develops a full interface for the program you write during the next hour. The program is a Lotto number cruncher that assesses a user’s chance of winning one of the multimillion dollar Lotto contests in the span of a lifetime. This chance is determined by running random six-number Lotto drawings again and again until the user’s numbers turn up as the big winner. Figure 14.6 shows the GUI you are developing for the application.

Figure 14.6. Displaying the GUI of the LottoMadness application.

Image

Create a new empty Java file called LottoMadness, enter text from Listing 14.2 into the source editor, and save the file.

Listing 14.2. The Full Text of LottoMadness.java


  1: import java.awt.*;
  2: import javax.swing.*;
  3:
  4: public class LottoMadness extends JFrame {
  5:
  6:     // set up row 1
  7:     JPanel row1 = new JPanel();
  8:     ButtonGroup option = new ButtonGroup();
  9:     JCheckBox quickpick = new JCheckBox("Quick Pick", false);
 10:     JCheckBox personal = new JCheckBox("Personal", true);
 11:     // set up row 2
 12:     JPanel row2 = new JPanel();
 13:     JLabel numbersLabel = new JLabel("Your picks: ", JLabel.RIGHT);
 14:     JTextField[] numbers = new JTextField[6];
 15:     JLabel winnersLabel = new JLabel("Winners: ", JLabel.RIGHT);
 16:     JTextField[] winners = new JTextField[6];
 17:     // set up row 3
 18:     JPanel row3 = new JPanel();
 19:     JButton stop = new JButton("Stop");
 20:     JButton play = new JButton("Play");
 21:     JButton reset = new JButton("Reset");
 22:     // set up row 4
 23:     JPanel row4 = new JPanel();
 24:     JLabel got3Label = new JLabel("3 of 6: ", JLabel.RIGHT);
 25:     JTextField got3 = new JTextField("0");
 26:     JLabel got4Label = new JLabel("4 of 6: ", JLabel.RIGHT);
 27:     JTextField got4 = new JTextField("0");
 28:     JLabel got5Label = new JLabel("5 of 6: ", JLabel.RIGHT);
 29:     JTextField got5 = new JTextField("0");
 30:     JLabel got6Label = new JLabel("6 of 6: ", JLabel.RIGHT);
 31:     JTextField got6 = new JTextField("0", 10);
 32:     JLabel drawingsLabel = new JLabel("Drawings: ", JLabel.RIGHT);
 33:     JTextField drawings = new JTextField("0");
 34:     JLabel yearsLabel = new JLabel("Years: ", JLabel.RIGHT);
 35:     JTextField years = new JTextField();
 36:
 37:     public LottoMadness() {
 38:         super("Lotto Madness");
 39:         setLookAndFeel();
 40:         setSize(550, 400);
 41:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 42:         GridLayout layout = new GridLayout(5, 1, 10, 10);
 43:         setLayout(layout);
 44:
 45:         FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,
 46:             10, 10);
 47:         option.add(quickpick);
 48:         option.add(personal);
 49:         row1.setLayout(layout1);
 50:         row1.add(quickpick);
 51:         row1.add(personal);
 52:         add(row1);
 53:
 54:         GridLayout layout2 = new GridLayout(2, 7, 10, 10);
 55:         row2.setLayout(layout2);
 56:         row2.add(numbersLabel);
 57:         for (int i = 0; i < 6; i++) {
 58:             numbers[i] = new JTextField();
 59:             row2.add(numbers[i]);
 60:         }
 61:         row2.add(winnersLabel);
 62:         for (int i = 0; i < 6; i++) {
 63:             winners[i] = new JTextField();
 64:             winners[i].setEditable(false);
 65:             row2.add(winners[i]);
 66:         }
 67:         add(row2);
 68:
 69:         FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER,
 70:             10, 10);
 71:         row3.setLayout(layout3);
 72:         stop.setEnabled(false);
 73:         row3.add(stop);
 74:         row3.add(play);
 75:         row3.add(reset);
 76:         add(row3);
 77:
 78:         GridLayout layout4 = new GridLayout(2, 3, 20, 10);
 79:         row4.setLayout(layout4);
 80:         row4.add(got3Label);
 81:         got3.setEditable(false);
 82:         row4.add(got3);
 83:         row4.add(got4Label);
 84:         got4.setEditable(false);
 85:         row4.add(got4);
 86:         row4.add(got5Label);
 87:         got5.setEditable(false);
 88:         row4.add(got5);
 89:         row4.add(got6Label);
 90:         got6.setEditable(false);
 91:         row4.add(got6);
 92:         row4.add(drawingsLabel);
 93:         drawings.setEditable(false);
 94:         row4.add(drawings);
 95:         row4.add(yearsLabel);
 96:         years.setEditable(false);
 97:         row4.add(years);
 98:         add(row4);
 99:
100:         setVisible(true);
101:     }
102:
103:     private void setLookAndFeel() {
104:         try {
105:             UIManager.setLookAndFeel(
106:                 "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
107:             );
108:         } catch (Exception exc) {
109:             // ignore error
110:         }
111:     }
112:
113:     public static void main(String[] arguments) {
114:         LottoMadness frame = new LottoMadness();
115:     }
116: }


Even though you haven’t added any statements that make the program do anything yet, you can run the application to make sure that the graphical interface is organized correctly and collects the information you need.

This application uses several different layout managers. To get a clearer picture of how the application’s user interface is laid out, take a look at Figure 14.7. The interface is divided into four horizontal rows that are separated by horizontal black lines in the figure. Each of these rows is a JPanel object, and the overall layout manager of the application organizes these rows into a GridLayout of four rows and one column.

Figure 14.7. Dividing the LottoMadness application into panels.

Image

Within the rows, different layout managers are used to determine how the components should appear. Rows 1 and 3 use FlowLayout objects. Lines 45–46 of the program show how these are created:

FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,
    10, 10);

Three arguments are used with the FlowLayout() constructor. The first argument, FlowLayout.CENTER, indicates that the components should be centered within their container—the horizontal JPanel on which they are placed. The last two components specify the width and height that each component should be moved away from other components. Using a width of 10 pixels and a height of 10 pixels puts a small amount of extra distance between the components.

Row 2 of the interface is laid out into a grid that is two rows tall and seven columns wide. The GridLayout() constructor also specifies that components should be set apart from other components by 10 pixels in each direction. Lines 54–55 set up this grid:

GridLayout layout2 = new GridLayout(2, 7, 10, 10);
row2.setLayout(layout2);

Row 4 uses GridLayout to arrange components into a grid that is two rows tall and three columns wide.

The LottoMadness application uses several components described during this hour. Lines 7–35 are used to set up objects for all the components that make up the interface. The statements are organized by row. First, a JPanel object for the row is created, and then each component that goes on the row is set up. This code creates all the components and containers, but they are not displayed unless an add() method is used to add them to the application’s main frame.

In Lines 45–98, the components are added. Lines 45–52 are indicative of the entire LottoMadness() constructor:

FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,
    10, 10);
option.add(quickpick);
option.add(personal);
row1.setLayout(layout1);
row1.add(quickpick);
row1.add(personal);
add(row1);

After a layout manager object is created, it is used with the setLayout() method of the row’s JPanel object—row1 in this case. When the layout has been specified, components are added to the JPanel by using its add() method. After all the components have been placed, the entire row1 object is added to the frame by calling its own add() method.

Summary

When you design a Java program’s GUI for the first time, you might have trouble believing that it’s an advantage for components to move around. Layout managers provide a way to develop an attractive GUI that is flexible enough to handle differences in presentation.

During the next hour, you learn more about the function of a GUI. You get a chance to see the LottoMadness interface in use as it churns through lottery drawings and tallies up winners.

Q&A

Q. Why are some of the text fields in the LottoMadness application shaded in gray while others are white?

A. The setEditable() method has been used on the gray fields to make them impossible to edit. The default behavior of a text field is to enable users to change the value of the text field by clicking within its borders and typing any desired changes. However, some fields are intended to display information rather than take input from the user. The setEditable() method prevents users from changing a field they should not modify.

Q. Was there a Willy Wonka golden ticket winner in Willy Wonka and the Chocolate Factory whose death was too horrible for the movie?

A. The fate of Miranda Piker was so gruesome that she was dropped from the final draft of Roald Dahl’s book Charlie and the Chocolate Factory, which inspired the 1971 movie and its 2005 remake. Piker was a smug child who believed children should never play so they could attend school all the time. Her father was a school headmaster.

Piker and the other kids at Wonka’s factory are introduced to Spotty Powder, a sugary concoction that causes the eater to break out in red spots so they can feign illness and miss school. Piker and her father become outraged and decide to destroy the machine that makes it.

As their screams are heard from the adjacent room, Wonka explains that they’ve gone into the place where the candy’s ingredients are ground into powder. “That’s part of the recipe,” he tells Miranda’s mother. “We’ve got to use one or two schoolmasters occasionally or it doesn’t work.”

The Oompa-Loompas celebrate her demise with song: “Oh, Miranda Mary Piker,/How could anybody like her,/Such a priggish and revolting little kid./So we said, ‘Why don’t we fix her/In the Spotty-Powder mixer/Then we’re bound to like her better than we did.’/Soon this child who is so vicious/Will have gotten quite delicious,/And her classmates will have surely understood/That instead of saying, ‘Miranda!/Oh, the beast! We cannot stand her!’/They’ll be saying, ‘Oh, how useful and how good!’”

Workshop

To see whether your brain cells are laid out properly, test your Java layout management skills by answering the following questions.

Quiz

1. What container is often used when subdividing an interface into different layout managers?

A. JWindow

B. JPanel

C. Container

2. What is the default layout manager for a panel?

A. FlowLayout

B. GridLayout

B. No default

3. The BorderLayout class gets its name from where?

A. The border of each component

B. The way components are organized along the borders of a container

C. Sheer capriciousness on the part of Java’s developers

Answers

1. B. JPanel, which is the simplest of the containers.

2. A. Panels use flow layout, but the default manager for frames and windows is grid layout.

3. B. You must specify the border position of components with the use of directional variables such as BorderLayout.WEST and BorderLayout.EAST as you add them to a container.

Activities

If you’d like to keep going with the flow (and the grid and the border), undertake the following activities:

• Create a modified version of the Crisis application with the panic and dontPanic objects organized under one layout manager and the remaining three buttons under another.

• Make a copy of the LottoMadness.java file that you can rename to NewMadness.java. Make changes to this program so the quick pick or personal choice is a combo box and the start, stop, and reset buttons are check boxes.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.31.22