Professional Documents
Culture Documents
Components
Layout Managers
Assigning the Layout Manager
FlowLayout Manager
FlowLayout Alignment
validate Method
BoxLayout Manager
BorderLayout Manager
Label Alignment
GridLayout Manager
Tic-Tac-Toe Program
Embedded Layout Managers
JPanel Class
MathCalculator Program
JTextArea Component
JCheckBox Component
JRadioButton Component
JComboBox Component
Job Application Example
2
Layout Managers
Layout managers automate the positioning of components within
containers.
They free the programmer from the difficult task of figuring out
the space needed for each component and the pixel coordinate
positions for each component.
The layout manager looks at the size of its container and the
sizes of the container's components. It then tries to fit the
components neatly into the container.
If a user resizes the window, the layout manager takes that into
account and adjusts the layout accordingly.
If a programmer adjusts a component's size (e.g., by changing a
label's font size), the layout manager takes that into account and
adjusts the layout accordingly.
3
Layout Managers
The five most common layout manager classes:
FlowLayout
BoxLayout
BorderLayout
GridLayout
GridBagLayout
Except for BoxLayout, all of these layout manager
classes are in the java.awt package. The
BoxLayout class is in the javax.swing package.
Import the appropriate package.
4
Assigning the Layout Manager
To assign a particular layout manager to a JFrame
window, call the setLayout method as follows:
setLayout(new <layout-manager-class>(<arguments>);
import javax.swing.*;
import java.awt.*;
public AfricanCountries()
{
setTitle("African Countries");
setSize(WIDTH, HEIGHT);
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new JButton("Tunisia"), BorderLayout.NORTH);
add(new JButton("<html>South<br>Africa</html>"), BorderLayout.SOUTH);
add(new JButton("Western Sahara"), BorderLayout.WEST);
add(new JButton("Central African Republic"), BorderLayout.CENTER);
add(new JButton("Somalia"), BorderLayout.EAST);
setVisible(true);
} // end AfricanCountries constructor
//**************************************
Case 1:
If you know the number of rows and columns in your table
and the table is completely filled in (i.e., there are no empty
cells), call the GridLayout constructor with the actual
number of rows and the actual number of columns.
Case 2:
Sometimes, you might want a row-oriented display.
If that's the case, call the GridLayout constructor with the
actual number of rows for the rows argument and 0 for the
columns argument.
A 0 for the columns argument indicates that you're leaving it
up to the GridLayout manager to determine the number of
columns.
25
Case 2 (continued):
Assume that you assign a container's layout like this:
setLayout(new GridLayout(2, 0));
Assume that you add 5 buttons to the container.
Here's the resulting display:
26
Case 3:
Sometimes, you might want a column-oriented display.
If that's the case, call the GridLayout constructor with the
actual number of columns for the columns argument and 0
for the rows argument.
Assume that you assign a container's layout like this:
setLayout(new GridLayout(0, 4));
After adding 5 buttons to the container, here's the resulting
display:
27
Common Errors
If you call the GridLayout constructor with 0's for both the rows and
columns arguments, you'll get a compilation error; i.e., this generates a
compilation error:
setLayout(new GridLayout(0, 0));
If you call the GridLayout constructor with non-0's for both the rows
and columns arguments and your table is not completely filled, you may
get unexpected results.
For example, the previous slide's four-column window is not completely
filled. Suppose you accidentally specify a value for the rows argument:
setLayout(new GridLayout(2, 4));
After adding 5 components to the container, here's the resulting display:
Tic-Tac-Toe Program
28
//***************************************
public TicTacToe()
{
setTitle("Tic-Tac-Toe");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
} // end TicTacToe constructor
Tic-Tac-Toe Program
29
//**************************************
//***************************************
//**************************************
Optional argument.
The default is FlowLayout with center alignment.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//***************************************
public MathCalculator()
{
setTitle("Math Calculator");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
} // end MathCalculator constructor
37
MathCalculator Program
//**************************************
//***************************************
try
{
x = Double.parseDouble(xBox.getText());
}
catch (NumberFormatException nfe)
{
x = -1; // indicates an invalid x
}
40
MathCalculator Program
if (e.getActionCommand().equals("sqrt x"))
{
if (x < 0)
{ getActionCommand
xSqrtBox.setText("undefined"); retrieves the label of the
} button that was clicked.
else
{
result = Math.sqrt(x);
xSqrtBox.setText(String.format("%7.5f", result));
}
} // end if
//**************************************
JTextArea
component
JCheckBox
component
43
JTextArea Component
To create a JTextArea component, call the
JTextArea constructor like this:
JTextArea <JTextArea-reference> = new JTextArea(<display-text>);
The display-text is the text that appears in the
JTextArea component. If the display-text argument
is omitted, then the JTextArea component displays
no initial text.
The size of a JTextArea component is the size of
the container that contains it.
In the license program, the JTextArea component
was placed in a border layout’s center region. If the
user enlarges the window size, the center region
expands, and the JTextArea box expands also.
44
JTextArea Component
The JTextArea class, like all the GUI component
classes, has quite a few methods. Here are the API
headings and descriptions for some of the more
popular JTextArea methods:
String getText()
Returns the text area's text.
void setText(String text)
Assigns the text area's text.
void setEditable(boolean flag)
Makes the text box editable or non-editable.
void setLineWrap(boolean flag)
Turns line wrap on or off.
void setWrapStyleWord(boolean flag)
Specifies whether word boundaries are used for line wrapping.
45
JTextArea Component
This code creates the components
private void createContents()
{ in the previously shown license
JTextArea license; agreement window.
JCheckBox confirmBox;
setLayout(new BorderLayout());
license = new JTextArea(
"SOFTWARE END-USER LICENSE AGREEMENT\n\n" +
"READ CAREFULLY: This Software End-User License Agreement" +
" is a legal agreement between us, the software provider, and" +
" you, the end user of a software product legitimately" +
" purchased from us. You must accept this agreement to" +
" complete the sale of the software license. If you do not" +
" accept this agreement, you forfeit all rights to your" +
" current and future property and progeny.");
license.setEditable(false);
license.setLineWrap(true);
license.setWrapStyleWord(true);
confirmBox = new JCheckBox(
"I accept the terms of this agreement.", true);
add(license, BorderLayout.CENTER);
add(confirmBox, BorderLayout.SOUTH);
} // end createContents
46
JCheckBox Component
JCheckBox component interface:
A JCheckBox component displays a small square with a label
at its right.
When the square is blank, the check box is unselected.
When the square contains a check mark, the check box is
selected.
Users click on the check box in order to toggle it between
selected and unselected.
47
JCheckBox Component
To create a JCheckBox component, call the
JCheckBox constructor like this:
JCheckBox <JCheckBox-reference> = new JCheckBox(<label>, <selected>);
//***************************************
public JobApplication()
{
setTitle("Job Application Form");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
} // end JobApplication constructor
61
Job Application Example
//**************************************
Without this line, our GridLayout components would touch the left edge of
the window. The setBorder call allows us to specify a border. The
EmptyBorder class allows us to specify widths (in pixels) for the top, left,
bottom, and right margins, respectively. The EmptyBorder class is in the
javax.swing.border package, so import that package.
62
Job Application Example
java = new JCheckBox("Oracle certified Java SE Programmer");
helpDesk = new JCheckBox("help-desk experience");
coffee = new JCheckBox("able to make good coffee");
goodCitizen = new JRadioButton("law-abiding citizen");
criminal = new JRadioButton("violent criminal");
radioGroup = new ButtonGroup();
radioGroup.add(goodCitizen);
radioGroup.add(criminal);
salary = new JComboBox(salaryOptions);
submit = new JButton("Submit");
submit.addActionListener(new ButtonListener());
//***************************************
//**************************************