Chapter 3
Chapter 3
Java GUI
6/7/2023 1
Introduction
Computer programs can use a console or a GUI to interact with the user
Console applications use text-based program output and keyboard entered user input.
GUIs use a graphical window or windows that provide interaction with the user.
GUI’s accept input from both the keyboard and a mouse, and a variety of other input devices.
A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an
application.
GUIs are built from GUI components. These are sometimes called controls or widgets. (short
for window gadgets—in other languages)
2
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 firstNum = JOptionPane.showInputDialog("Enter first integer―);
int number1 = Integer.parseInt(firstNum);
String secondNum = JOptionPane.showInputDialog("Enter second integer" );
int number2 = Integer.parseInt( secondNum );
int sum = number1 + number2; // add numbers
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
}}
3
Cont …
Java’s JOptionPane class (package javax.swing) provides prepackaged dialog boxes for both
input and output.
6
Cont …
For every platform on which Java runs, the AWT components are automatically mapped
Not truly portable: looks different and lays out inconsistently on different OSs. The
Is adequate for many applications but it is difficult to build an attractive GUI.
7
Cont …
Swing GUI components allow you to specify a uniform look-and-feel for your
application across all platforms.
8
AWT vs Swing…
• Swing is built ―on top of‖ AWT, so you need to import AWT and use a few
things from it.
• Swing and AWT are incompatible:- you can use either, but you can’t mix them.
9
AWT vs Swing…
• Swing gives far more options for everything (buttons with pictures on them, etc.)
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.
11
1. GUI Container 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 container that includes a panel.
12
Cont …
The terms ―pane‖ and ―panel‖ are used interchangeably in Java.
Every frame has at least one pane, the default ―Content Pane‖.
JApplet
13
2. GUI Component Classes…
GUI Components or Controls (also known as "widgets")
• Are the basic user interface elements the user interacts with: labels, buttons, text
fields, ...
• When the user does something to a component, the component's listener is sent an
event.
14
Swing GUI Components
JCheckBoxMenuItem
JMenuItem JMenu
JToggleButton JCheckBox
JRadioButton
JComponent JEditorPane
JTextArea
16
Swing GUI Components …
More complex displays
• Tables (JTable)
• Trees (JTree)
• Formatted Text
• Properties
JButton
• Methods
• Events
17
3. GUI Helper Classes
GUI Helper Classes
They are used to describe the properties of GUI components such as graphics context,
colors, fonts, and dimension.
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 colors of lines, shapes,…..
18
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.
Font f=new Font();
LayoutManager
Is an interface whose instances specify how components are arranged in a
container.
The helper classes are in the java.awt package.
• The Swing components do not replace all the classes in AWT, only AWT GUI
components classes (e.g. Button, TextField, TextArea).
• The AWT helper classes remain unchanged.
19
GUI Helper Classes
FontMetrics
Graphics
Lightweight
20
20
Steps to build a GUI
1. Make a Container:– you need to create either a frame or an applet to hold the user-
interface components.
21
Creating a Frames
Frame
• Is an independent window that has decorations such as a border, a title and buttons for
closing, minimizing and maximizing the window.
• Frame is a window that is not contained inside another window.
• Can be moved around on the screen independently of any other GUI windows.
• Frame is the basis to contain other user interface components in Java GUI applications.
22
Creating a Frames
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. 23
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.
26
JFrame…
Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) tells the program to
terminate when the frame is closed.
• Thus the program does not terminate when the frame is closed.
• Since JFrame is subclass of Frame, you can use it to set a title for an object of JFrame.
27
GUI Components
• Introduces the frequently used GUI components
JButton
Component Container JComponent AbstractButton JCheckBox
JToggleButton
JRadioButton
JLabel
JTextArea
JTextComponent
JTextField JPasswordField
JComboBox
JList
JScrollBar
JSlider
28
28
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.
29
29
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.
30
30
JButton
JButton Properties/Data Fields
text
icon
mnemonic
horizontalAlignment
verticalAlignment
horizontalTextPosition
verticalTextPosition
iconTextGap
31
31
Some Useful JButton Methods
public void setText(String text)
• Sets the button's text. JButton button= new JButton();
public String getText() button.setText(“Click Here”); OR
• Returns the button's text. JButton button= new JButton(“Click Here");
public void setEnabled(boolean b)
• Enables (or disables) the button.
public void setSelectedIcon(Icon selectedIcon)
• Sets the selected icon for the button.
public boolean isSelected()
• Returns the state of the button. True if the
toggle button is selected, false if it's not.
32
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)
+JLabel(text:
33 String, hAlignment: int) Creates a label with text and the specified horizontal alignment.
33
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 a text and the specified horizontal
alignment.
JLabel(Icon icon, int horizontalAlignment)
• Creates a label with an icon and the specified horizontal
alignment.
JLabel(String text, Icon icon, int horizontalAlignment)
• Creates a label with text, an icon, and the specified horizontal
alignment.
34
34
JLabel
JLabel Properties
• JLabel inherits all the properties from JComponent and has many properties similar to the ones in JButton,
such as text, icon, horizontalAlignment,verticalAlignment, horizontalTextPosition, verticalTextPosition,
and iconTextGap.
// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);
36
36
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.
•Text fields are useful in that they enable the user to enter in variable data.
•JTextField is swing class for an editable text display.
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.
37columns: int)
+JTextField(text: String, Creates a text field initialized with the specified text and columns.
37
JTextField
JTextField Constructors: JTextField Properties
• JTextField() • text
Creates a default empty text field with number of columns set to 0. • horizontalAlignment
• JTextField(int columns)
• editable
Creates an empty text field with the specified number of columns.
• 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.
38
JTextField
• public String getText()
Returns the string from the text field.
• public void setText(String text)
Puts the given string in the text field.
• public void setEditable(boolean editable)
Enables or disables the text field to be edited. By default, editable is true.
• public void setColumns(int)
Sets the number of columns in this text field.The length of the text field is changeable.
text.setEditable(false);
add(Fname); add(text); add(Lname); add(text1);
40
40
JPasswordField….
• Allows the editing of a single line of text where the view indicates something was typed, but does
not show the original characters.
42
JTextArea
• If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them.
• The solution is to use JTextArea class, which enables the user to enter multiple lines of text.
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 columns.
+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.
43 43
JTextArea….
JTextArea Constructors JTextArea Properties:
• text
JTextArea(int rows, int columns)
• editable
Creates a text area with the specified number of
• columns
rows and columns.
• lineWrap
JTextArea(String s, int rows, int columns) • wrapStyleWord
Creates a text area with the initial text and • rows
the number of rows and columns specified. • lineCount
• tabSize
44
44
JTextArea
Text Area
45
JTextArea…
46
JCheckBox
JCheckBox is a widget that has two states. On and Off. It is a box with a label.
47
47
JCheckBox …
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 check
selected: boolean) box is initially selected.
48
48
JCheckBox …
JCheckBox Constructor Summary
• JCheckBox()
Creates an initially unselected check box button with no text, no icon.
• JCheckBox(Icon icon)
Creates an initially unselected check box with an icon.
• JCheckBox(Icon icon, boolean selected)
Creates a check box with an icon and specifies whether or not it is initially selected.
• JCheckBox(String text)
Creates an initially unselected check box with text.
49
JCheckBox…
50
JRadioButton
51
51
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.
52
52
JRadioButton
53
JRadioButton…
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.
+setSelectionMode(selectionMode: int): Sets the selection mode for the list.
55 55
Jlist …
JList Constructors
• JList(): Creates an empty list.
Jlist Methods
void setSelectionMode(int selectionMode)
Determines whether single-item or multiple-item selections are allowed.
selectionMode:- is one of the three values (SINGLE_SELECTION,
SINGLE_INTERVAL_SELECTION, MULTIPLE_INTERVAL_SELECTION).
int getSelectionMode()
Returns whether single-item or multiple-item selections are allowed.
Object[] getSelectedValues()
• Returns an array of the values for the selected cells.
56
56
JList Methods…
Object getSelectedValue()
• Returns the first selected value, or null if the selection is empty.
void setListData(Object[ ] listData)
• Constructs a ListModel from an array of objects and then applies setModel to it.
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 selected item.
57
57
JList…
JList Properties
• selectedIndexd
• selectedIndices
• selectedValue
• selectedValues
• selectionMode
• visibleRowCount
58
58
Jlist…
String[] str={“Math”,”Computer”,”Physics”,”Chemistry”};
JList list = new JList(str);
JPanel p = new JPanel();
p.add(list);
59
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.
60
60
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.
61
61
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.
62
62
JComboBox….
63
63
Menu Components
64
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);
}
}
65
Adding Components into a Frame
• Each JFrame contains a content pane.
• The GUI components such as buttons are placed in the content pane in a
frame.
• Prior to JDK 1.5, you have to use the getContentPane() method in the
JFrame class to return the content pane of the frame, and then invoke the
content pane’s add method to place a component into a content pane.
66
Adding Components into a Frame
• This was cumbersome, JDK 1.5 allows you to place the components to the content pane
by invoking a frame’s add method.
• Strictly speaking, a component is added into the content pane of the frame.
67
Adding Components into a Frame
OR
frame.getContentPane().add(new JButton("OK"));
Title bar
Content pane
68
68
Adding Components into a Frame
Content pane
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // New since JDK 1.4
}
}
70
Adding Components into a Frame
71
Adding Components into a Frame
In the next section, you will use several different layout managers to
place components in other location as desired.
72
Layout Management
• Layouts tell Java where to put components in containers (JPanel, content pane, etc).
• If you don't specify otherwise, the container will use a default layout manager.
• Every panel (and other container) has a default layout, but it's better to set the layout
explicitly for clarity.
73
Layout Management
Example:
LayoutManager layoutManager = new XLayout();
container.setLayout(layoutManager);
74
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
75
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.
76
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.
77
77
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));
}
78
FlowLayout
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
79
BorderLayout
80
BorderLayout…
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).
81
81
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));
82
BorderLayout…
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowBorderLayout");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
83
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).
85
85
GridLayout … example
import javax.swing.*;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
Output:
87
GridLayout …
You can specify the number of rows and columns in the grid.
The basic rules are as follows:
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.
For example: if you specify three rows and zero columns for a grid that has ten
components, GridLayout creates three fixed rows of four columns, with the last
row contains two components.
88
GridLayout …
If both the number of rows and the number of columns are nonzero, the number of
rows is the dominating parameter; that is, the number of rows is fixed, and the
layout manager dynamically calculates the number of columns.
For example: if you specify three rows and three columns for a grid that has ten
components , GridLayout creates three fixed rows of four columns, with the last
row containing two components.
89
GridBagLayout
• GridBagLayout lays out components based on a grid with rows and columns that
need not all be the same size.
• GridBagLayout is the most sophisticated, flexible layout manager the Java
platform provides.
• For each component there are eleven constraint values.
• GridBagConstraint properties:
90
GridBagConstraint properties:
• int gridx ( >=0 ) :The column in which the component is placed (It starts at 0)
• int gridy(>= 0 ) :The row in which the component is placed (It starts at 0)
• int gridwidth (>= 1 ) :The number of columns the component occupies
• int gridheight( >=1 ) The number of rows the component occupies
• int fill : Specifies how the component is to be enlarged to fill its allocated region.
• Valid values are:
• GridBagConstraints.NONE – doesn’t resize the component (Default).
• GridBagConstraints.HORIZONTAL - make the component wide enough to fill
its display area horizontally, but don't change its height
• GridBagConstraints.VERTICAL - make the component tall enough to fill its
display area vertically, but don't change its width.
• GridBagConstraints.BOTH - make the component fill its display area entirely.
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.
92
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.
public void setResizable(boolean resizable)
• 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.
• You would like to group related components together, and then to lay out the groups in the
frame. This is where panels are useful.
93
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:
1. Decide on how to divide the frame into panels.
2. Add GUI components to panels .
3. Add the panels to the frame.
• Each panel has its own layout manager.
• The default layout manager of JPanel is Flowlayout, which is often ideal, but you may
use another layout manager if appropriate.
• When the panels are added to a frame, the frame's layout manager arranges the panels as
if each panel were a single component.
94
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.
• 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 object to that panel.
95
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);
JPanel p1 = new JPanel();
JPanel p = new JPanel();
p1.add(p);
f.add(p1);
96
Adding Components to JPanels
• The default layout manager, for JPanel is FlowLayout, so
setLayout() does not need to be called.
Example 1: Create a window which looks like the following:
97
Adding Components to JPanels
1.Create Components 2.Create Panels
JLabel lb1 = new JLabel("Percent of Calories from Fat"); JPanel p1 = new JPanel();
Jlabel lbl2 = new JLabel("Enter grams of fat: "); JPanel p2 = new JPanel();
Jlabel lbl3 = new JLabel("Enter total calories: "); Jpanel p3 = new JPanel();
Jlabel lbl4 = new JLabel("Percent calories from fat: "); JPanel p4 = new JPanel();
JTextField txt1 = new JTextField( 7 ); JPanel p5 = new JPanel();
JTextField txt2 = new JTextField( 7 ); 3.Add Components to Panel
p1.add( lb1 );
JTextField txt3 = new JTextField( 7 ); 4.Add Panel into the Frame
p2.add( lbl2 );
p2.add( txt1 ); setLayout( new FlowLayout());
JButton jbt1 = new JButton("Do It!");
p3.add( lbl3 ); add( p1 );
p3.add( txt2 ); add( p2 );
p4.add( lbl4 ); add( p3 );
p4.add( txt3); add( p4 );
p5.add( jbt1 );
add( p5 );
98
Adding Components to JPanels
Example 2: Create a window which looks like the following:
1.Create Components
JLabel lData1 = new JLabel("Data Item 1");
JLabel lData2 = new JLabel("Data Item 2");
JLabel lData3 = new JLabel("Data Item 3");
JTextField txData1 = new JTextField( 7 );
JTextField txData2 = new JTextField( 7 );
JTextField txData3 = new JTextField( 7 );
2.Create Panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
4.Add Panel into the Frame 3. Add Components to Panel
setLayout( new FlowLayout()); panel1.add( lData1 );
panel1.add( txData1 );
add( panel1 ); panel2.add( lData2 );
panel2.add( txData2 );
add( panel2 ); panel3.add( lData3 );
panel3.add( txData3 );
add( panel3 ); 99
Adding Components to JPanels
Exercise : Create a window which looks like the
following:
100
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
alignment
101
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) );
102
Adding Components to JPanels
Example 1 : Create a window which looks like the following:
103
Adding Components to JPanels
104
Adding Components to JPanels
• Set layout manager for left panel, add three small panels to it:
105
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);
106
Adding Components to JPanels
• Add left and right panels to the frame
107
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);
108
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);
}
}
109
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
110
}
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
}
}
111