Chapter 1 GUI
Chapter 1 GUI
Chapter 1 GUI
4
Simple GUI-Based I/O with JOptionPane
The following simple addition application uses two input dialogs to
obtain integers from the user and a message dialog to display the
sum of the integers the user enters.
import javax.swing.JOptionPane;
public class Addition {
public static void main( String args[] ) {
String firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
int number1 = Integer.parseInt( firstNumber );
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
int number2 = Integer.parseInt( secondNumber );
int sum = number1 + number2; // add numbers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
5 }
}
Simple GUI-Based …
Java’s JOptionPane class (package javax.swing) provides
prepackaged dialog boxes for both input and output.
These dialogs are displayed by invoking static JOptionPane
methods.
showInputDialog method displays an input dialog using the
method’s String argument ("Enter first integer") as a prompt . It
has a text box and two buttons ok and Cancel
showMessageDialog method is used to display a message dialog
containing the sum.
The first argument helps the Java application determine where
to position the dialog box.
The value null indicates that the dialog should appear in the
center.
6
It can also be used to specify that the dialog should appear
centered over a particular window of the computer screen.
Simple GUI-Based…
The second argument is the message to display—in this
case, the result of concatenating the String "The sum is "
and the value of sum.
The third argument—"Sum of Two Integers"—represents
the string that should appear in the dialog’s title bar at the
top of the dialog.
The fourth argument:- JOptionPane.PLAIN_MESSAGE
—is the type of message dialog to display. A
PLAIN_MESSAGE dialog does not display an icon to the
left of the message. Other possible constants are:
ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE
Class JOptionPane provides several overloaded
versions of methods showInputDialog and
7
showMessageDialog, as well as methods that display
AWT vs Swing
Java has two GUI packages, the original Abstract
Windows Toolkit (AWT) and the newer Swing.
When java was introduced, the GUI classes were
bundled in a library known as Abstract Windows
Toolkit(AWT).
AWT (Abstract Window Toolkit) is Java’s original
set of classes for building GUIs.
Uses peer components of the OS; heavyweight
AWT uses the native operating system's window
routines so the visual effect is dependent on the run-
8
time system platform.
AWT vs Swing
For every platform on which Java runs, the AWT
components are automatically mapped to the
platform-specific components through their
respective agents, known as peers.
Not truly portable: looks different and lays out
inconsistently on different OSs. The application's
GUI components display differently on each
platform.
AWT is adequate for many applications but it is
difficult to build an attractive GUI
9
AWT vs Swing
Swing is designed to solve AWT’s problems (present
since Java 2 )
99% java; lightweight components
Drawing of components is done in java
Swing GUI components allow you to specify a
uniform look-and-feel for your application across all
platforms.
Lays out consistently on all Oss
Much bigger set of built-in components
Uses AWT event handling
10
AWT vs Swing…
Swing is built “on top of” AWT, so you need to import
AWT and use a few things from it
Swing is bigger and slower
Swing is more flexible and better looking
Swing and AWT are incompatible--you can use either,
but you can’t mix them
Actually, you can, but it’s tricky and not worth doing
Basic components/controls are practically the same in
both
AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");
Swing gives far more options for everything (buttons
with pictures on them, etc.)
11 AWT classes are contained inside package java.awt
while swing classes are located in package javax.swing.
GUI Class Hierarchy
FontMetrics
Graphics
Lightweight
12 12
GUI Classes
The GUI classes can be classified into three groups:
container class, helper class, and component classes.
Container classes
A GUI is built by putting components/controls into
containers.
Container is used to group components. Frames,
Panels and applets are examples of containers.
Important Container classes are JFrame, JApplet,
and JPanel.
13
GUI Classes
JFrame
A resizable, movable window with title bar and
close button. Usually it contains JPanels.
It is a containers that holds other Swing user-
interface components in Java GUI application.
JPanel
A region internal to a JFrame or another JPanel.
Used for grouping components together. Optionally
bounded by a visible border. Lives inside some
enclosing Container.
Panels can be nested. You can place panels inside a
14 container that includes a panel.
GUI Classes…
The terms “pane” and “panel” are used
interchangeably in Java.
If a frame is a window, a pane is the glass.
Panes hold a window’s GUI components.
Every frame has at least one pane, the default
“Content Pane”
JApplet
Is a subclass of Applet .
represents the featureless Window provided by the
browser for an Applet to run in.
15
Container Classes
FontMetrics
Graphics
16 16
GUI Classes…
17
Swing GUI Components
JCheckBoxMenuItem
JMenuItem JMenu
JToggleButton JCheckBox
JRadioButton
JComponent JEditorPane
JTextArea
Methods JButton
Events
20
GUI Class…
GUI Helper Classes
Graphics
Is an abstract class that provides a graphical context for
drawings strings, lines, and simple shapes.
Color:
Deals with the colors of GUI components.
For example:- you can specify background colors in
components like Jframe and Jpanel. You can specify
21
colors of lines, shapes,…..
GUI Class…
Font
Specify fonts for the text and drawings on GUI
components.
Example:- You can specify the font type(e.g.
SansSerif), style (e.g. bold), and size(e.g. 24 points) for
the text on the button.
LayoutManager
Is an interface whose instances specify how
components are arranged in a container.
FontMetrics
Graphics
Lightweight
23 23
Steps to build a GUI
26
Frame
27
JFrame
JFrame()
Constructs a new frame with no title and it is
initially
invisible.
JFrame(String title)
Creates a new, initially invisible Frame with the
specified
title.
28
JFrames…
JFrame Class Methods
javax.swing.JFrame
+setSize(width: int, height: int): void Specifies the size of the frame.
+setLocation(x: int, y: int): void Specifies the upper-left corner location of the frame.
+setVisible(visible: boolean): void Sets true to display the frame.
+setDefaultCloseOperation(mode: int): void Specifies the operation when the frame is closed.
+setLocationRelativeTo (c: Component):
void Sets the location of the frame relative to the specified
component. If the component is null, the frame is centered
on the screen.
29 29
JFrames…
JFrame
public Class
void Methods
setBounds(int x, int y, int width, int
height)
• Specifies the size of the frame and the location of the
upper
left corner.
• This puts the upper left corner at location (x, y), where
x the
the number of pixels from the left of the screen and y is
is the
number from the top of the screen. height and width are
as
30
before.
30
JFrames…
JFrame Class Methods
public void setDefaultCloseOperation(int mode)
31 31
JFrame…
import javax.swing.*;
public class JFrameSample {
public static void main(String[] args) {
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
32
JFrame…
• The frame is not display until the
frame.setVisibile(true) method is invoked.
• Invoking setLocationRelativeTo(null)centers
33
the frame on the screen.
JFrame…
Invoking
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
tells the program to terminate when the frame is
closed.
}
}
35
JFrame…
37
GUI Components
Introduces the frequently used GUI components
JButton
Component Container JComponent AbstractButton JCheckBox
JToggleButton
JLabel JRadioButton
JTextArea
JTextComponent
JTextField JPasswordField
JComboBox
JList
JScrollBar
JSlider
38 38
JButton
A button is a component that triggers an action
event
when clicked.
• Swing provides regular buttons, toggle buttons,
check
box buttons, and radio buttons.
• The common features of these buttons are
generalized in
javax.swing.AbstractButton.
• JButton inherits AbstractButton and provides
several
39 39
JButton
JButton Constructors.
javax.swing.AbstractButton
javax.swing.JButton
+JButton() Creates a default button with no text and icon.
+JButton(icon: javax.swing.Icon) Creates a button with an icon.
+JButton(text: String) Creates a button with text.
+JButton(text: String, icon: Icon) Creates a button with text and an icon.
40 40
JButton
The following are JButton constructors:
JButton()
Creates a default button with no text and icon.
JButton(Icon icon)
Creates a button with an icon.
JButton(String text)
Creates a button with text.
text
icon
mnemonic
horizontalAlignment
verticalAlignment
horizontalTextPosition
verticalTextPosition
iconTextGap
43 43
JButton
Some Useful JButton Methods
45
JLabel
A label is a display area for a short text(a non-editable),
an image, or both.
javax.swing.JComponent
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JLabel
-text: String The label’s text.
-icon: javax.swing.Icon The label’s image icon.
-horizontalAlignment: int The horizontal alignment of the text and icon on the label.
-horizontalTextPosition: int The horizontal text position relative to the icon on the label.
-verticalAlignment: int The vertical alignment of the text and icon on the label.
-verticalTextPosition: int The vertical text position relative to the icon on the label.
-iconTextGap: int The gap between the text and the icon on the label (JDK 1.4).
+JLabel() Creates a default label with no text and icon.
+JLabel(icon: javax.swing.Icon) Creates a label with an icon.
+JLabel(icon: Icon, hAlignment: int) Creates a label with an icon and the specified horizontal alignment.
+JLabel(text: String) Creates a label with text.
+JLabel(text: String, icon: Icon, Creates a label with text, an icon, and the specified horizontal alignment.
hAlignment: int)
46 +JLabel(text:
46 String, hAlignment: int) Creates a label with text and the specified horizontal alignment.
JLabel
The constructors for labels are as follows
JLabel()
• Creates a default label with no text and icon.
JLabel(String text)
• Creates a label with text.
JLabel(Icon icon)
• Creates a label with an icon.
JLabel(String text, int horizontalAlignment)
• Creates a label with an text and the specified horizontal
alignment.
47 47
JLabel
JLabel Properties
49 49
JLabel Jlabel…
Some Useful JLabel Methods
51 51
JTextField
A text field is a box that contains a line of text. The
user can
type text into the box and the program can get it and
then use
it as data.
The program can write the results of a calculation to a
Text Field.
Text fields are useful in that they enable the user to
enter in
variable data (such as a name or a description).
JTextField is swing class for an editable text display.
52 52
JTextField
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.text.JTextComponent
-text: String The text contained in this text component.
-editable: boolean Indicates whether this text component is editable (default: true).
javax.swing.JTextField
-columns: int The number of columns in this text field.
-horizontalAlignment: int The horizontal alignment of this text field (default: LEFT).
+JTextField() Creates a default empty text field with number of columns set to 0.
+JTextField(column: int) Creates an empty text field with specified number of columns.
+JTextField(text: String) Creates a text field initialized with the specified text.
+JTextField(text: String, columns: int) Creates a text field initialized with the specified text and columns.
53 53
JTextField
JTextField Constructors:
JTextField(int columns)
Creates an empty text field with the specified number of
columns.
JTextField(String text)
Creates a text field initialized with the specified text.
JTextField(String text, int columns)
Creates a text field initialized with the specified text and the
column size.
54 54
JTextField
JTextField Properties
text
horizontalAlignment
editable
columns
55 55
JTextField
JTextField Methods
jtf.setEditable(false);
add(Fname); add(text); add(Lname); add(text1);
58 58
JPasswordField….
59
JPasswordField…
JPasswordField Constructor Summary
JPasswordField()
Constructs a new JPasswordField, with a default document, null
starting text string, and 0 column width.
JPasswordField(int columns)
Constructs a new empty JPasswordField with the specified
number of columns.
JPasswordField(String text)
Constructs a new JPasswordField initialized with the specified
text.
JPasswordField(String text, int columns)
Constructs a new JPasswordField initialized with the specified
text
60 and columns.
JPasswordField….
61
JTextArea
62 62
JTextArea….
javax.swing.text.JTextComponent The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JTextArea
-columns: int The number of columns in this text area.
-rows: int The number of rows in this text area.
-tabSize: int The number of characters used to expand tabs (default: 8).
-lineWrap: boolean Indicates whether the line in the text area is automatically wrapped (default:
false).
-wrapStyleWord: boolean Indicates whether the line is wrapped on words or characters (default: false)
+JTextArea() Creates a default empty text area.
+JTextArea(rows: int, columns: int) Creates an empty text area with the specified number of rows and columns.
+JTextArea(text: String) Creates a new text area with the specified text displayed.
+JTextArea(text: String, rows: int, columns: int) Creates a new text area with the specified text and number of rows and colu
+append(s: String): void Appends the string to text in the text area.
+insert(s: String, pos: int): void Inserts string s in the specified position in the text area.
+replaceRange(s: String, start: int, end: int): Replaces partial text in the range from position start to end with string s.
void
+getLineCount(): int Returns the actual number of lines contained in the text area.
63 63
JTextArea….
JTextArea Constructors
64 64
JTextArea….
JTextArea Properties:
text
editable
columns
lineWrap
wrapStyleWord
rows
lineCount
tabSize
65 65
JTextArea
Text Area
66
JTextArea…
67
JCheckBox
JCheckBox is a widget that has two states. On and Off. It is
a box with a label.
If the checkbox is checked, it is represented by a tick in a
box.
javax.swing.AbstractButton
javax.swing.JToggleButton
javax.swing.JCheckBox
+JCheckBox() Creates a default check box button with no text and icon.
+JCheckBox(text: String) Creates a check box with text.
+JCheckBox(text: String, selected: Creates a check box with text and specifies whether the check box is
boolean) initially selected.
+JCheckBox(icon: Icon) Creates a checkbox with an icon.
+JCheckBox(text: String, icon: Icon) Creates a checkbox with text and an icon.
+JCheckBox(text: String, icon: Icon, Creates a check box with text and an icon, and specifies whether the chec
selected: boolean) box is initially selected.
69 69
JCheckBox …
JCheckBox(String text, boolean selected)
Creates a check box with text and specifies whether or not it is
initially selected.
JCheckBox(String text, Icon icon)
Creates an initially unselected check box with the specified text
and icon.
JCheckBox(String text, Icon icon, boolean selected)
Creates a check box with text and icon, and specifies whether
or not it is initially selected.
71
JCheckBox…
73 73
JRadioButton
javax.swing.AbstractButton
javax.swing.JToggleButton
javax.swing.JRadioButton
+JRadioButton() Creates a default radio button with no text and icon.
+JRadioButton(text: String) Creates a radio button with text.
+JRadioButton(text: String, selected: Creates a radio button with text and specifies whether the radio button is
boolean) initially selected.
+JRadioButton(icon: Icon) Creates a radio button with an icon.
+JRadioButton(text: String, icon: Icon) Creates a radio button with text and an icon.
+JRadioButton(text: String, icon: Icon, Creates a radio button with text and an icon, and specifies whether the radio
selected: boolean) button is initially selected.
74 74
JRadioButton
JRadioButton bird = new JRadioButton("Bird");
JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
add(bird);
add(cat);
add(dog);
75
JRadioButton…
JRadioButton bird = new JRadioButton("Bird");
JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
add(bird); add(cat); add(dog);
ButtonGroup bg = new ButtonGroup();
bg.add(bird); bg.add(cat); bg.add(dog);
76
JList
77 77
JList…
javax.swing.JComponent
javax.swing.JList
+JList() Creates a default empty list.
+JList(items: Object[]) Creates a list that contains the elements in the specified array.
+getSelectedIndex(): int Returns the index of the first selected item.
+setSelectedIndex(index: int): void Selects the cell at the specified index.
+getSelectedIndices(): int[] Returns an array of all of the selected indices in increasing order.
+setSelectedIndices(indices: int[]): void Selects the cells at the specified indices.
+getSelectedValue(): Object Returns the first selected item in the list.
+getSelectedValues(): Object[] Returns an array of the values for the selected cells in increasing index order.
+getVisibleRowCount(): int Returns the number of visible rows displayed without a scrollbar. (default: 8)
+setVisibleRowCount(count: int): void Sets the preferred number of visible rows displayed without a scrollbar.
+getSelectionBackground(): Color Returns the background color of the selected cells.
+setSelectionBackground(c: Color): void Sets the background color of the selected cells.
+getSelectionForeground(): Color Returns the foreground color of the selected cells.
+setSelectionForeground(c: Color): void Sets the foreground color of the selected cells.
+getSelectionMode(): int Returns the selection mode for the list.
78 +setSelectionMode(selectionMode:
78 int): Sets the selection mode for the list.
JList…
JList Constructors
79 79
JList…
Jlist Methods
void setSelectionMode(int selectionMode)
Determines whether single-item or multiple-item selections are
allowed.
int getSelectionMode()
Returns whether single-item or multiple-item selections are
allowed.
80
80
JList…
Jlist Methods
Object[] getSelectedValues()
Returns an array of the values for the selected cells.
Object getSelectedValue()
Returns the first selected value, or null if the selection is empty.
81 81
JList…
Jlist Methods
Color getSelectionBackground()
Returns the background color for selected cells.
Color getSelectionForeground()
Returns the selection foreground color.
void setSelectionBackground(Color selectionBackground)
Sets the background color for selected cells.
void setSelectionForeground(Color selectionForeground)
Sets the foreground color for selected cells.
int getSelectedIndex()
Returns the first selected index; returns -1 if there is no
82
selected
82 item.
JList…
JList Properties
selectedIndexd
selectedIndices
selectedValue
selectedValues
selectionMode
visibleRowCount
83 83
Jlist…
String[] str={“Math”,”Computer”,”Physics”,”Chemistry”};
JList list = new JList(str);
JPanel p = new JPanel();
p.add(list);
84
JComboBox
A combo box is a simple list of items from which the
user can choose. It performs basically the same function
as a list, but can get only one value.
javax.swing.JComponent
javax.swing.JComboBox
+JComboBox() Creates a default empty combo box.
+JComboBox(items: Object[]) Creates a combo box that contains the elements in the specified array.
+addItem(item: Object): void Adds an item to the combo box.
+getItemAt(index: int): Object Returns the item at the specified index.
+getItemCount(): int Returns the number of items in the combo box.
+getSelectedIndex(): int Returns the index of the selected item.
+setSelectedIndex(index: int): void Sets the selected index in the combo box.
+getSelectedItem(): Object Returns the selected item.
+setSelectedItem(item: Object): void Sets the selected item in the combo box.
+removeItem(anObject: Object): void Removes an item from the item list.
+removeItemAt(anIndex: int): void Removes the item at the specified index in the combo box.
+removeAllItems(): void Removes all items in the combo box.
85 85
JComboBox….
JComboBox Methods
void addItem(Object AnObject)
Adds an item to the item list.
Object getItemAt(int index)
Returns the list item at the specified index.
int getItemCount()
Returns the number of items in the list.
int getSelectedIndex()
Returns the first item in the list that matches the given
item.
86 86
JComboBox….
JComboBox Methods
Object getSelectedItem()
Returns the current selected item.
void removeAllItems()
Removes all items from the item list.
void removeItem(Object anObject)
Removes an item from the item list.
void removeItemAt(int anIndex)
Removes the item at anIndex This method works only if the
JComboBox uses a mutable data model.
void setEnabled(boolean b)
Enables the combo box so that items can be selected.
87 87
JComboBox….
String[] petStrings = { "Bird", "Cat", "Dog",
"Rabbit", "Pig" };
//Create the combo box, select item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
88
Menu Components
89
Menu Components…
import java.awt.*;import javax.swing.*;
public class MainClass {
public static void main(String args[]) {
JFrame f = new JFrame("JMenuBar Sample");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Sample Menu");
/JMenuItem menuItem1=new JMenuItem(“Sub Menu 1”);
menu.add(menuItem1);
JMenuItem menuIte2 = new JMenuItem(“Sub Menu 2”);
menu.add(menuItem2);
JMenuItem menuItem3 = new JMenuItem(“Sub Menu 3”);
menu.add(menuItem3);
bar.add(menu);
f.setJMenuBar(bar);
}
}
90
Adding Components into a
Frame
Each JFrame contains a content pane.
92
Adding Components into a
// Add
Frame
a button into the frame
Jbutton jbt = new Jbutton(“OK”);
frame.getContentPane().add(jbt);
OR
frame.getContentPane().add(new JButton("OK"));
Title bar
Content
pane
93 93
Adding Components into a
Frame
Content Pane Delegation in JDK 1.5
Title bar // Add a button into the frame
Jbutton jbt = new Jbutton(“OK”);
frame.getContentPane().add(jbt);
OR
frame.getContentPane().add(new JButton("OK"));
Content pane
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // New since JDK 1.4
}
}
95
Adding Components into a
Frame
The add(component c) method defined in the
container class adds an instance of component.
96
Adding Components into a
Frame
When you run the above program MyFrameWithComponents,
the button is always centered in the frame and occupies the
entire frame no matter how you resize it.
In the next section, you will use several different layout
managers to place components in other location as desired.
97
Layout Management
Layouts tell Java where to put components in
containers (JPanel, content pane, etc).
Layout manager is created using layout manager class.
Every layout manager class implements the
LayoutManager class.
Each layout manager has a different style of
positioning components. If you don't specify
otherwise, the container will use a default layout
manager.
Example:
LayoutManager layoutManager = new XLayout();
container.setLayout(layoutManager);
99
Layout Management…
BorderLayout GridLayout
FlowLayout
Left to right, w e
c
Top to bottom
none,
One at a time JButton programmer
sets x,y,w,h
100
FlowLayout
Simplest layout manager.
Components are placed left to right in the order in
which they were added. When one row is filled, a
new row is started.
Components can be right aligned, centered or left
aligned by using FlowLayout.RIGHT,
FlowLayout.CENTER, and FlowLayout.LEFT
respectivley.
The FlowLayout manager is
part of the java.awt package.
101
FlowLayout Class
The get and set methods for these data fields are provided in
java.awt.FlowLayout the class, but omitted in the UML diagram for brevity.
102 102
FlowLayout
import javax.swing.*;
import java.awt.*;
public class ShowFlowLayout extends JFrame {
public ShowFlowLayout() {
// Set FlowLayout, aligned left with horizontal gap 10
// and vertical gap 20 between components
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
103
FlowLayout
frame.setTitle("ShowFlowLayout");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
104
BorderLayout
The BorderLayout manager divides the window into
five areas: East, South, West, North, and Center.
At most five components can be added.
If you want more components, add a Panel, then add
components to it.
The get and set methods for these data fields are provided in
java.awt.BorderLayout the class, but omitted in the UML diagram for brevity.
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).
106 106
BorderLayout …
import javax.swing.*;
import java.awt.BorderLayout;
public class ShowFlowLayout extends JFrame {
public ShowFlowLayout() {
// Set BorderLayout with horizontal gap 5 and vertical
gap 10
setLayout(new BorderLayout(5, 10));
108
GridLayout
The GridLayout manager divides the container up into a
given number of rows and columns:
new GridLayout(rows, columns)
All sections of the grid are equally sized and as large as
possible
The get and set methods for these data fields are provided in
java.awt.GridLayout the class, but omitted in the UML diagram for brevity.
-rows: int The number of rows in this layout manager (default: 1).
-columns: int The number of columns in this layout manager (default: 1).
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).
110 110
GridLayout … example
import javax.swing.*;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
Output:
112
GridLayout …
You can specify the number of rows and columns in the
grid.
The basic rules are as follows:
I. The number of rows or the number of columns can be
zero. But not both. If one is zero and the other is
nonzero, nonzero dimension is fixed, while the zero
dimension is determined dynamically by the layout
manager.
115
BoxLayout
BoxLayout arranges components either horizontally or
vertically in a panel.
You can control alignment and spacing of the components.
Complicated layouts can be made by combining many
panels, some with horizontal layout and some with vertical
layouts.
116
Using Panels as Sub container
When the user resizes the frame the layout of
components can change drastically.
FlowLayout does not keep related items together. It
just puts them in the rows one after another as they are
added.
This section discusses how to better control the layout
process.
One method for ensuring that a graphical interface
looks the way you intend is setResizable method of
JFrame. So that you can prevent the user from
resizing it.
117
public void setResizable(boolean
Using Panels as Sub container
If the parameter is false then the user cannot resize
the frame.
But this does not solve all problems. When a frame
contains several logical groups of components it may
be difficult to lay them out correctly using a single
layout manager.
118
Using Panels as Sub container
A JPanel is a container that is used to group
components together.
Panels do not have visible edges.
To layout components using JPanels:
120
Adding Components to JPanels
You can use new JPanel() to create a panel with the
default FlowLayout manager or new
JPanel(LayoutManager) to create a panel with the
specified layout manager.
Use the Add(Component c) method to add a
component to the panel.
You need to say which container (which panel) gets
each component.
Syntax:
whichPanel.add(ComponentObjectRefVar);
means run the add() method of whichPanel to add the
121
object to that panel.
Adding Components to JPanels
For example:- The following code creates a panel and
adds a button to it.
JPanel p = new JPanel();
p.add(new JbButton(“OK”));
Panels can be placed inside a frame or inside another
panel.
JFrame f = new JFrame();
JPanel p = new JPanel();
f.add(p);
123
Adding Components to JPanels
Create Components
JLabel lb1 = new JLabel("Percent of Calories from Fat");
Jlabel lbl2 = new JLabel("Enter grams of fat: ");
Jlabel lbl3 = new JLabel("Enter total calories: ");
Jlabel lbl4 = new JLabel("Percent calories from fat: ");
125
Adding Components to JPanels
Add Components to Panel
p1.add( lb1 );
p2.add( lbl2 );
p2.add( txt1 );
p3.add( lbl3 );
p3.add( txt2 );
p4.add( lbl4 );
p4.add( txt3);
add( p1 );
add( p2 );
add( p3 );
add( p4 );
add( p5 );
127
Adding Components to JPanels
Example 2: Create a window which looks like the
following:
128
Adding Components to JPanels
Create Components
129
Adding Components to JPanels
Create Panels
130
Adding Components to JPanels
Add Components to Panel
panel1.add( lData1 );
panel1.add( txData1 );
panel2.add( lData2 );
panel2.add( txData2 );
panel3.add( lData3 );
panel3.add( txData3 );
131
Adding Components to JPanels
Add Panel into the Frame
add( panel1 );
add( panel2 );
add( panel3 );
132
Adding Components to JPanels
Exercise : Create a window which looks like the
following:
133
Adding Components to JPanels
BoxLayout
Sometimes you want components to be lined up in a
strictly vertical (or strictly horizontal) order. This can
be done with a BoxLayout layout manager.
Here is a constructor for it:
BoxLayout(Container contain, int axis)
contain: the container this layout manager is for
axis: BoxLayout.X_AXIS — for left to right
alignment
BoxLayout.Y_AXIS — for top to bottom
134 alignment
Adding Components to JPanels
Notice that the constructor needs a reference to the
container that it is managing.
To set the layout manager of a JPanel to BoxLayout
with vertical alignment, do this:
JPanel panel = new JPanel();
panel.setLayout( new BoxLayout( panel,
BoxLayout.Y_AXIS) );
135
Adding Components to JPanels
Example 1 : Create a window which looks like the
following:
136
Adding Components to JPanels
• Add components into the panel
panel1.add( lData1 ); panel1.add( txData1 );
panel2.add( lData2 ); panel2.add( txData2 );
panel3.add( lData3 ); panel3.add( txData3 );
panel4.add( lData4 ); panel4.add( txData4 );
panel5.add( lData5 ); panel5.add( txData5 );
panel6.add( lData6 ); panel6.add( txData6 );
137
Adding Components to JPanels
• Set layout manager for left panel, add
three small panels to it:
138
Adding Components to JPanels
• Set layout manager for right panel, add
three small panels to it:
pnRight.setLayout( new BoxLayout( pnRight,
BoxLayout.Y_AXIS ) );
pnRight.add( panel4);
pnRight.add( panel5);
pnRight.add( panel6);
139
Adding Components to JPanels
• Add left and right panels to the frame
140
Example
Layout Managers can be used together
import java.awt.*;
import javax.swing.*;
public class TestPanels extends JFrame {
public TestPanels() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++)
p1.add(new JButton("" + i));
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));
JPanel p2 = new JPanel(new BorderLayout());
p2.add(new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
141
Example
p2.add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.EAST);
add(new JButton("Food to be placed here"),
BorderLayout.CENTER);
}
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 250);
frame.setVisible(true);
}
}
142
Jpanel…
import java.awt.*;
import javax.swing.*;
public class MainClass extends JFrame {
private JPanel buttonJPanel; // panel to hold buttons
private JButton buttons[]; // array of buttons
public MainClass(){ // no-argument constructor
super( "Panel Demo" );
buttons = new JButton[ 5 ]; // create buttons array
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout( 1, buttons.length ) );
for (int i=0;i<buttons.length;i++){
buttons[i] = new JButton("Button "+(i+1));
buttonJPanel.add( buttons[i]);
add( buttonJPanel, BorderLayout.SOUTH );
} // end PanelFrame constructor
} // end class PanelFrame
143
}
JPanel…
class PanelDemo extends JFrame {
public static void main( String args[] ){
MainClass panelFrame = new MainClass();
panelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
panelFrame.setSize( 450, 200 ); // set frame size
panelFrame.setVisible( true ); // display frame
}
}
144
Reading Assignment
Constructors and Methods of all
components and Layout Managers
discussed in this lecture
145