Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
113 views121 pages

Chapter 3 GUI in Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 121

Chapter 3

AWT and Swing


(GUI in Java)

1 Advanced Programming with Java Chapter 1 02/21/2024


AWT Vs Swing
There are two sets of java API for graphics programming
1/awt(Abstract window toolkit)
• Sun initial idea.
• Not powerful enough.
To import packages containing awt component and container
Import java.awt.*;
Example. Frame,Dialog,Panel,Applet,Button…..

2/Swing
• Second Edition
• Allow much power full computer graphics.
• Use prefix “J” to differentiate it from awt
components and containers
o To import packages containing swing component and container
import javax.swing.*;

Example JFrame,JDialog,JPanel,JApplet,JButton…..

2
AWT vs Swing
 AWT is Java’s original set of classes for building
GUIs
 Uses peer components of the OS; heavyweight
components. Each heavyweight component has a
peer (from package java.awt.peer) that is
responsible for the interactions between the
component and the local platform that display and
manipulate the component.
 Not truly portable: looks different and lays out
inconsistently on different Oss
 Due to OS’s underlying display management system

3 Advanced Programming with Java Chapter 1 02/21/2024


Con’t…
 Swing is designed to solve AWT’s problems
– 99% java; lightweight components
• Drawing of components is done in java
• Uses AWTs components like Window, frame,
dialog
– Lays out consistently on all OSs
– Uses AWT event handling
– Swing provides several advanced components such
as tabbed pane, scroll panes, trees, tables and
lists.
– Unlike AWT components, Swing components are
not implemented by platform-specific code.
Instead they are written entirely in Java and
therefore are platform-independent. The term
"lightweight" is used to describe such an element
4 Advanced Programming with Java Chapter 1 02/21/2024
Con’t…
 Swing provides replacements for most of the AWT
components, although many AWT non-component
classes remain in use.
 Mixing both Swing and AWT components in the
same interface can produce errors, so one has to
make a decision about which to use. Despite the
advantages of Swing, there actually are arguments
for using AWT.
 Swing advantages
 Swing is faster.
 Swing is more complete.
 Swing is being actively improved

5 Advanced Programming with Java Chapter 1 02/21/2024


Con’t…
 AWT advantages
 AWT is supported on older, as well as newer,
browsers so Applets written in AWT will run on
more browsers.
 The Java Micro-Edition, which is used for
phones, TV settup boxes,etc, uses AWT, not
Swing

6 Advanced Programming with Java Chapter 1 02/21/2024


Swing
 Swing is Java's GUI(graphical user interface)
library
 So far, our user interfaces have only been textual,
meaning the user sees text and writes text at the
command prompt.
 Swing is created to provide a more sophisticated
set of GUI components than the Abstract
Windows Toolkit (AWT)
 Today we will learn to make our interfaces
graphical, so we can use our programs through
windows, click on buttons, etc.
 You MUST import the following packages to use
swing:
import java.awt.*;
import javax.swing.*;
7 Advanced Programming with Java Chapter 1 02/21/2024
Con’t…
 Swing is a Java package, javax.swing, provided in
J2SDK (Java 2 Software Development Kit). It
provides many enhancements to the existing
graphics package, AWT (Abstract Windows
Toolkit) package, java.awt.
 javax.swing and java.awt together offer a complete
API (Application Programming Interface) for Java
applications to operate graphical devices and
create GUI (Graphical User Interfaces).
 The Swing components are implemented entirely in
the Java programming language.

8 Advanced Programming with Java Chapter 1 02/21/2024


What are Components?
 A component is an object having a graphical
representation that can be displayed on the
screen. like checkboxes, menus, windows,
buttons, text fields, applets, and more.
 A container is a special component that can hold
other components.
Example of containers in typical GUI applications
include:
panels, windows, applets, frames
 Functionality of most GUI components derive
from the Component and Container classes.

9 Advanced Programming with Java Chapter 1 02/21/2024


Components Hierarchy

10 Advanced Programming with Java Chapter 1 02/21/2024


Swing Containment Hierarchy
 Top-level container:
• place for other Swing components to paint
themselves
• e.g., JFrame, JDialog

11 Advanced Programming with Java Chapter 1 02/21/2024


Swing Containment Hierarchy
 Intermediate container:
• simplify positioning of atomic components
• e.g., JPanel, JSplitPane, JTabbedPane

12 Advanced Programming with Java Chapter 1 02/21/2024


Swing Containment Hierarchy
 Atomic components:
• self-sufficient components that present
information to and get input from the user
• e.g., JButton, JLabel, JComboBox,
JTextField, JTable

13 Advanced Programming with Java Chapter 1 02/21/2024


Implementing a Swing GUI
 Import javax.swing.*, java.awt.*
 Make a specific class to do GUI functions
 Specify all the GUI functions/components in the
class’s constructor (or methods / classes called by
the constructor)
 Run the GUI by instantiating the class in the
class’s main method

14 Advanced Programming with Java Chapter 1 02/21/2024


My First Swing Program
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
// let’s create a frame object and give some title
JFrame frame = new JFrame("HelloWorldSwing");
// let’s have a label
JLabel label = new JLabel("Hello World");
//let’s add the label to the frame we have created above
frame.getContentPane().add(label);
//this is the operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//pack() causes a window to be sized to fit the preferred
//size and layouts of its sub-components
frame.pack(); // let’s make the frame to be visible
frame.setVisible(true);
}
}
15 Advanced Programming with Java Chapter 1 02/21/2024
15
Example 2
import javax.swing.*;
public class HelloWorldFrame extends JFrame {
In this example a
public HelloWorldFrame() { custom frame is
super(“HelloWorldSwing”); created

final JLabel label = new JLabel("Hello World");


getContentPane().add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
HelloWorldFrame frame = new HelloWorldFrame();
}
}

16 Advanced Programming with Java Chapter 1 02/21/2024


Components
 Components (also known as "widgets") are the basic user
interface elements the user interacts with: labels,
buttons, text fields, ...
 Components are placed in a container (eg, JPanel). The
visual arrangement of the components depends on the
container's layout. When the user does something to a
component, the component's listener is sent an event.

17 Advanced Programming with Java Chapter 1 02/21/2024


Components cont'd...
The most important components to learn for simple programs
are:
Input Components
Buttons ( JButton, Radio Buttons, JCheckBox)
Text (JTextField, JTextArea)
Menus (JMenuBar, JMenu, JMenuItem)
Sliders (JSlider)
JComboBox (uneditable) (JComboBox)
Information Display Components
JLabel
Progress bars (JProgressBar)
Tool tips (using JComponent's setToolTipText(s) method)

18 Advanced Programming with Java Chapter 1 02/21/2024


Components cont'd...
Choosers

 File chooser (JFileChooser)

 Color chooser (JColorChooser)

More complex displays


 Tables (JTable)

 Trees (JTree)

19 Advanced Programming with Java Chapter 1 02/21/2024


Components cont'd...
Components and Their Description

Jlabel: An area where uneditable text or icons can be displayed.

JTextField :An area in which the user inputs data from the
keyboard. The area can also display information.

Jbutton: An area that triggers an event when clicked.

JcheckBox: A GUI component that is either selected or not
selected.

JcomboBox: A drop-down list of items from which the user can
make a selection by clicking an item in the list or possibly by
typing into the box.

Jlist: An area where a list of items is displayed from which the
user can make a selection by clicking once on any element in the
list. Double-clicking an element in the list generates an action
event. Multiple elements can be selected.

Jpanel: A container in which components can be placed.

20 Advanced Programming with Java Chapter 1 02/21/2024


Top-level Container: javax.swing.JFrame

21 Advanced Programming with Java Chapter 1 02/21/2024


Anatomy of a JFrame
title bar

minimize
maximize
close

The contentPane holds your


content; created automatically
when a JFrame is created
22 Advanced Programming with Java Chapter 1 02/21/2024
JFrame
 JFrame is the application window class
 It draws the window and interacts with the operating
system
 When a JFrame is created, an inner container called
the contentPane is automatically created
 We don't draw graphics directly on JFrame; we draw
on the contentPane
 Frames are the basis of any Java GUI
 Frame is the actual window that encompasses your
GUI objects; a GUI can have multiple frames
 The “J” prefix is at the beginning of any Swing
component’s name (to distinguish them from AWT
components)
23 Advanced Programming with Java Chapter 1 02/21/2024
JFrame
 The javax.swing.JFrame class is used to create a
"window". This window has a few characteristics of its
own (title bar, etc), but most of the controls are placed
in one of two subareas: content pane or menu bar.
 You can create a frame like this:
JFrame w = new JFrame("your title");
// but it's better to use subclassing as below.
 Subclass JFrame, build in constructor. Another better
way is to define a class, eg on page 16 class
HelloWorldFrame that extends JFrame, put the code
which builds the GUI in the class's constructor, and
create an instance of the window from the main program.

24 Advanced Programming with Java Chapter 1 02/21/2024


Jframe(cont)
 Content pane - Two styles - Get it or Set it
There are two common ways to use a JFrame's content
pane. Both are commonly used. In both cases, the easiest
style is to assign the working version of the content pane.
 Get the predefined content pane and change it. Every
JFrame comes with a default content pane. It doesn't
have anything on it, although it does have a default
layout, probably not the one you want to use though! The
getContentPane() method returns a Container object,
which interestingly is actually a Jpanel.
 Create a JPanel and make it the content pane. This
requires a call to setContentPane(...).

25 Advanced Programming with Java Chapter 1 02/21/2024


Using the content pane.
Jframe(cont)
c= w.getContentPane(); Returns window's content pane.

w.setContentPane(c); Sets window's content pane to c (or subclass


JPanel).
Handling the window's close box.
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE This adds a window
); listener that simply
executes System.exit(). It's
the short, appropriate,
solution for most small
programs.
w.addWindowListener(listen); Use this to call your own
window closing listener.
Executing the layout.
w.pack(); Finalize layout after everything is added to window and content
pane. Don't use validate() with layout managers.

26 Advanced Programming with Java Chapter 1 02/21/2024


Jframe(cont)
Displaying the window.
w.setVisible(true); Makes the window visible, and starts the Event Dispatch
Thread (EDT) which manages the GUI. This is usually called
by the main program after calling the constructor. show()
should no longer be used.
Miscellaneous.
w.setTitle(title); xxx
w.setResizable(false); Set to false if you don't want the user to resize your
window.
w.setJMenuBar(mbar); This is how to add a menubar to the window.
w.setLocationRelativeTo(null) Centers the window. If you even bother with position,
; this is the most common choice.
Less common positioning and sizing.
w.setSize(w, h); Sets window to pixel width (w) and height (h). The only reasons
to use this are to fill the screen or restore a window size from a
previous run.
w.setLocation(x, Sets the upper left corner of the window to this screen pixel
y); coordinate.

27 Advanced Programming with Java Chapter 1 02/21/2024


Jframe(cont) Window Size and Position
 First pack your window to do the layout : The optimum
size of a window depends on the size and layout of the
components. After adding all the components to a window
(JFrame), call pack() to perform the layout.
 Centering a Window : The following code positions a
window (JFrame) f in the center of the screen. Use this
when you create a window, after calling pack() has been
called, as follows.
setLocationRelativeTo(null);
// Implicit "this" if inside JFrame constructor.
f.setLocationRelativeTo(null);
// Explicit JFrame if outside JFrame constructor.

28 Advanced Programming with Java Chapter 1 02/21/2024


Jframe(cont) Content Panes
 Before Java 2 each top-level container had only one
layer. Java 2 top-level containers (JFrame, JApplet, ...)
have several layers (panes): root, content, layered, and
glass. Programs normally reference only the content
pane. There are two programming idioms for using the
content pane:
(1) using the preassigned pane (recommended), or
(2) building your own pane.

 Naming convention
 It is common to name the content pane content or content
Pane.

29 Advanced Programming with Java Chapter 1 02/21/2024


Jframe(cont) Content Panes
 Idiom 1: Use the existing content pane
 Each container has a pre constructed content pane of
class Container. You can get this pane and add the
components to it. For example,
class MyWindow extends JFrame {
. . .
MyWindow() {
// constructor
Container content = getContentPane();
// Use the default content pane.
content.add(...);
content.add(...);
. . .
}

30 Advanced Programming with Java Chapter 1 02/21/2024
Jframe(cont) Content Panes
 All JFrames already have a content pane, so there's no
need to create a new one, just get the existing pane. And
if you're wondering about the Container type, it's a
superclass of JPanel. In fact, if you look at the actual
type of the object that's currently returned by
getContentPane(), it really is a Jpanel.
 Sometimes programmers don't bother to copy the
content pane reference into a new variable, resulting in
code like this. Since there are typically a large number
of references to the content pane, this seems awkward.
class MyWindow extends JFrame {
MyWindow() {
// constructor
getContentPane().add(...);
getContentPane().add(...);
. . .

31 Advanced Programming with Java Chapter 1 02/21/2024


Jframe(cont) Content Panes
 Idiom 2: Create your own content pane
It's common to create a new panel for the content pane
and tell the window to use this new panel for it's content
pane. For example,
class MyWindow extends JFrame {
MyWindow() {
// constructor
JPanel content = new JPanel();
// Create a new content pane.
content.add(...);
content.add(...);
. . .
setContentPane(content);
}
}

32 Advanced Programming with Java Chapter 1 02/21/2024


Where to declare components
 Components are typically declared in one of several places:
 Field variables : Some components should be declared as field
variables (instance variables, member variables). This is the
appropriate place to declare components which must be referenced
after the interface is constructed. Typically these are text fields or
text areas, check boxes, etc. Those components whose values must be
gotten or set.
 Local variables : Local variables should be used for components which
are never referenced after the interface is constructed. Typically
these are panels for holding components, buttons (whose interaction is
through their listeners), ... Local variables disappear when the method
they are in returns, but the component will continue to exist if it has
been added to the interface.
 Anonymous : Anonymous creation is typical with labels, which can be
created and added in one step and never assigned to a variable. Of
course, if the appearance (font, alignment, ...) must be changed, then
they should be put in a local variable. Some programs use labels for
output (not a good idea), and in this case they should be field variables .
Example content.add(new JLabel("Look at this"));

33 Advanced Programming with Java Chapter 1 02/21/2024


JLabel
 Labels display fixed text or images on a GUI as
information to the user, for example, as a label in front
of a JTextField, etc. You can have text (including HTML),
an image, or both on a JLabel. A JLabel has a transparent
background, so it will always match the container it is in.
 JLabel Constructors
Assume the following declarations.
String text;
Icon image;
int alignment; // JLabel.LEFT, JLabel.Center, or JLabel.RIGHT.
JLabel yourLabel = new JLabel(text);
JLabel yourLabel = new JLabel(text, alignment);
JLabel yourLabel = new JLabel(image);
JLabel yourLabel = new JLabel(image, alignment);
JLabel yourLabel = new JLabel(text, image, alignment);

34 Advanced Programming with Java Chapter 1 02/21/2024


Jlabel(cont)
 Java Idiom
Because there is usually no need to refer to a JLabel after it
has been added to a container, it is common to combine
creation and adding the JLabel in one statement.
For example.
...
p.add(new JLabel("Enter your ID:", JLabel.RIGHT));
is the same as
JLabel idLabel = new JLabel("Enter ID:", JLabel.RIGHT);
. . .
p.add(idLabel);

35 Advanced Programming with Java Chapter 1 02/21/2024


Jlabel(cont)
 JLabel font and color
The most user-friendly interfaces are usually obtained by
using the default appearance (font, color, background), but
there are cases where you want to change these.
 Appearance: setting the font
The font of a JLabel can be changed like this.

JLabel title = new JLabel(“Enter Name :", JLabel.CENTER);


title.setFont(new Font("Serif", Font.BOLD, 48));

36 Advanced Programming with Java Chapter 1 02/21/2024


Jlabel(cont)
 Appearance: setting the text color
Use the setForeground method to set the text color.
JLabel title = new JLabel(“Name :", JLabel.CENTER);
title.setForeground(Color.white);
 Appearance: setting the background color
Because a JLabel's background is transparent, there is no
effect from using the setBackground method. To make a
new background, you need to create a JPanel with the
appropriate color and put the label on that. For example
JLabel title = new JLabel(“Enter your name");
title.setForeground(Color.white);
JPanel titlePanel = new JPanel(); titlePanel.setBackground(Color.blue);
titlePanel.add(title);

37 Advanced Programming with Java Chapter 1 02/21/2024


Jlabel(cont)JLabel for output
 Why using JLabel for output is usually bad
It's possible to change the text of a JLabel, although this is not
generally a good idea after the user interface is already
displayed. For output JTextField is often a better choice. The
use of JLabel for output is mentioned because some textbooks
display output this way. Here are some reasons not to use it.
 Can't copy to clipboard. The user can not copy text from a
JLabel, but can from a JTextField.
 Can't set background. Changing the background of individual
components probably isn't a good idea, so this restriction on
JLabels is not serious. You can change the background of a
JTextField, for better or worse.
 Text length. This is where there are some serious issues. You
can always see the entire text in a JTextField, although you
might have to scroll it it's long. There are several possibilities
with a JLabel. You may either not see all of the long text in a
JLabel, or putting long text into a JLabel may cause the layout
to be recomputed, resulting in a truly weird user experience.

38 Advanced Programming with Java Chapter 1 02/21/2024


Jlabel(cont)
 Changing the text of a JLabel
Most JLabels are never changed, except for
internationalization, and that is done before the user
interface is shown. To change the text, use
yourLabel.setText(String newText);

39 Advanced Programming with Java Chapter 1 02/21/2024


JTextField
 javax.swing.JTextField has two uses.
 Input. The user can enter one line of text (a String)
 Output. To display one line of text.
 If you need a component that displays or allows
entry of more than one line, use a JTextArea.
 Overview of methods
JTextField
JTextField(width)
setText(text)
String getText()
addActionListener(listener)
setEditable(true/false)
setFont(font)
setHorizontalAlignment(align)
requestFocus(align)
40 Advanced Programming with Java Chapter 1 02/21/2024
JTextField(cont)
To use a JTextField for Input
1.Declare a JTextField as an instance variable. Reason: If it's an
instance variable, it can be seen in all methods in the class.
2.Assign an initial value to this variable by calling the JTextField
constructor. Specify the approximate field width in the
constructor. Example:
JTextField yourInpuField = new JTextField(16);
3.Add the text field to a container.
content.add(yourInputField);
or to add it to a JPanel p
p.add(yourInputField);
4. Input is done by calling the getText().
 Get the string in the text field by calling yourTextField.getText()
method whenever you need it. This is probably the most common
way.
String x = yourInputField.getText();
 Attach an action listener to the text field. It is called whenever
the user types Enter in that field. The listener can then get the
text and process it.
41
Advanced Programming with Java Chapter 1 02/21/2024
JTextField(cont)
To use a JTextField for Output
0 Using a JTextField for output is almost the same as for input,
but .
1. Set the text field with yourTextField.setText(someString)
2.If it's only for output, call .setEditable(false) so the user can't
change the field. Here is the sequence.
3.Declare and initialize a JTextField as a field variable (instance
variable). Example:
1. JTextField myOutput = new JTextField(16);
You can also set the initial value in the field
JTextField myOutput = new JTextField("someInitialValue", 20);
2. Add the text field to a container. For example, to add it to
JPanel p. p.add(myOutput);
3. Setting the value of the text field. Whenever you want put a
string value in the text field, call myOutput.setText("Some text").
myOutput.setText("some text");
42 Advanced Programming with Java Chapter 1 02/21/2024
JTextField(cont)
 Constructors
JTextField tf = new JTextField(int columns);
The number of columns is approximate because the width of
text depends on the font and width of individual characters.

JTextField tf = new JTextField(String initial);


This puts the initial String in the JTextField. The size of the
JTextField is set from this String.

JTextField tf = new JTextField(String initial, int columns);


This creates a JTextField columns wide with value initial.

43 Advanced Programming with Java Chapter 1 02/21/2024


JTextField(cont)
Common methods
 Here are some of the most common methods use with text fields:
Assume these declarations
JTextField tf;
ActionListener listener;
String s,
text;
Font f; //--- When used for input.
s = tf.getText(); // gets the text from the JTextField
tf.addActionListener(listener);// Optional listener intialization.
//--- When used for output.
tf.setText(text); // Sets text in the JTextField.
tf.setEditable(false); // Initialization to disallow user changes.
//--- To change the appearance.
tf.setHorizontalAlignment(align);//See below for possible values.
tf.setFont(f); // sets the font for the text
44 Advanced Programming with Java Chapter 1 02/21/2024
JTextField(cont)
Appearance of a JTextField - font, alignment
0 yourField.setFont(Font f); sets the font for the text. Often numbers
are aligned to the right (eg, in the display of a calculator), and text is
aligned to the left.
0 yourField.setHorizontalAlignment(align); sets the alignment of the text
in the field, where align is one of these values: JTextField.LEFT (the
default), JTextField.CENTER, or JTextField.RIGHT.
0 Example
JTextField userID; // declare a field . . .
userID = new JTextField(8); // create field approx 8 columns wide.
p.add(userID); // add it to a JPanel
userID.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
... // THIS CODE IS EXECUTED WHEN RETURN IS TYPED
}
}
45); Advanced Programming with Java Chapter 1 02/21/2024
JTextField(cont)
Use JPasswordField for passwords
 Use a JPasswordField component for a field where the
characters the person enters are replaced by some other
character. JPasswordField is a subclass of JTextField.

Use JFormattedTextField to restrict input format


 The JPasswordField subclass of JTextField can be used to
restrict the input to particular values.

Focus
 To select a JTextField so that user typing occurs in that
field, you must give the JTextField focus. For example, the
nameField JTextField can be given focus with:
nameField.requestFocus();

46 Advanced Programming with Java Chapter 1 02/21/2024


JTextArea
 A javax.swing.JTextArea is a multi-line text component to
display text or allow the user to enter text.
 Using a JTextArea for output -- Setting the text
 Assume: JTextArea ta;
int i, w, pos, start, end, line;
String s; boolean b;
Font f;
Result Method Description
Constructors
ta = new JTextArea(rows, cols); Creates text area. cols is approx char
width.
ta = new JTextArea(s, rows, cols); As above, but also containing initial
string s.

47 Advanced Programming with Java Chapter 1 02/21/2024


JTextArea(cont)
Result Method Description
Setting text
ta.setText(s); Replaces all text with s.
ta.append(s); Appends s to the end.
ta.insert(s, pos); Inserts s at position pos.
ta.replaceRange(s, start, end); Replace start to end with s.
Getting text
s = ta.getText(); Returns all text. Use methods below to get
individual lines.
i = ta.getLineCount(); Returns number of lines in the text area.
i = ta.getLineStartOffset(line); Returns character index of beginning of line
line. May throw
javax.swing.text.BadLocationException.
i = ta.getLineEndOffset(line); Returns character index of end of line line.
May throw
javax.swing.text.BadLocationException.

48 Advanced Programming with Java Chapter 1 02/21/2024


JTextArea(cont)
Scrolling
 JTextArea doesn't support scrolling itself but you can
easily add the JTextArea to a JScrollPane. JScrollPane
creates scrollbars as needed. For example,

//... Create scrolling text area.


resultTA = new JTextArea("This is a test", 10, 80); JScrollPane
scrollingResult = new JScrollPane(resultTA);
content.add(scrollingResult);

49 Advanced Programming with Java Chapter 1 02/21/2024


JTextArea(cont)
public class TextAreaDemoB extends JFrame {
JTextArea _resultArea = new JTextArea(6, 20);
public TextAreaDemoB() {
//... Set textarea's initial text, scrolling, and border.
_resultArea.setText("Enter more text to see scrollbars");
JScrollPane scrollingArea = new JScrollPane(_resultArea);
//... Get the content pane, set layout, add to center
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
//... Set window characteristics.
this.setContentPane(content);
this.setTitle("TextAreaDemo B");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack(); }
public main public static void main(String[] args) {
JFrame win = new TextAreaDemoB();
win.setVisible(true);
}
Advanced Programming with Java Chapter 1
}50 02/21/2024
Java: Buttons
There are many kinds of buttons, all derived from the AbstractButton
class.

Components Description
JButton This is a standard button which can have text,
icon, or both.
Listener: addActionListener(...)

JCheckBox The box next to the text can be toggled on or off.


JRadioButton, ButtonGroup Radio buttons are a group of buttons that can have
at most one button toggled on. When you click one
button, that button is toggled on, and all others are
set to off.

JMenuItem Menu items are a kind of button.


JToggleButton Changes between two states: on and off. Stays
on/off until the next click.

51 Advanced Programming with Java Chapter 1 02/21/2024



JButton
There are a few steps in using a button: declaring it, creating it,
adding it to a container (the content pane or a JPanel), and adding a
listener that has code to execute when the user clicks on the
button. Images can be used on buttons, including automatic rollover
effects.
 Constructors
 Assume these declarations.
String text;
Icon image;
JButton btn = new JButton(text);
JButton btn = new JButton(text, image);
JButton btn = new JButton(image); Common methods
 Assume these declarations:
JButton btn;
ActionListener listener;
boolean b;
//--- Buttons always have action listeners.
btn.addActionListener(listener);
btn.setEnabled(b);
52 Advanced Programming with Java Chapter 1 02/21/2024

Jbutton(cont)
Events : When a button is clicked, the actionPerformed() method
is called for all of the button's listeners. It is passed an
ActionEvent, which is generally ignored, but can be used to identify
which component generated the event if several share the same
listener. The example below shows the creation of a button,
attaching a listener, and adding the button to a container.
 Example
 Typically a button is assigned to a local variable (not an instance
variable) and an anonymous action listener is added to it. The
listener often calls another method to do everything because
separating the code to build the user interface and do the
"semantics" makes a program clearer and easier to modify.
JButton mybtn = new JButton("Do Something");
mybtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
doMyAction(); // code to execute when button is pressed
}
}
); . . .
content.add(mybtn); // add the button to a JPanel (eg, content).
53 Advanced Programming with Java Chapter 1 02/21/2024
Jbutton(cont) JButton Appearance
 Dynamically changing a button
 You can change the text or icon (image) that appears
on a button with:
btn.setText("someText");
btn.setIcon(anIcon);
 WARNING: If you change the size of the button by
one of these changes, this may have consequences in
the layout of the components. This may require a call
to validate() or revalidate() which then computes a new
layout based on the change in the button size. This is
not a quick operation. Replacing an icon with another of
the same size should not cause any problems.

54 Advanced Programming with Java Chapter 1 02/21/2024


Jbutton(cont)
Buttons with Icons
 You can create buttons that show text, icons (images), or
both. Different images can be associated with different
button states and user interactions with the button
(disabled, rollover, ...). The two supported image formats
are GIF and JPEG, although support for more image types
is being worked on.

 To create a button with an icon


JButton next = new JButton(new ImageIcon("right.gif"));
or
JButton next = new JButton("Next", rightArrow);

55 Advanced Programming with Java Chapter 1 02/21/2024


JComboBox (uneditable)
Making Choices
 There are several ways to select one of many fixed choices: radio
buttons, a menu, a list, or a (uneditable) combo box. A combo box
(JComboBox) is a popup menu and is often the best component to use
because it uses less space than radio buttons or a list, and it shows
as part of a "form" so the user realizes it's there, unlike a menu.
You can also use an editable combo box, and in this case the user can
either choose from the pop-up menu or type in a value.
Constructor
 An easy way to build a combo box is to initialize an array (or Vector,
but not yet the new Collections types) of strings and pass it to the
constructor. Objects other than strings can be used, but this is the
most common. The list also be built by successive calls to the add
method.
String[] dias = {"lunes", "martes", "miercoles"};
JComboBox dayChoice = new JComboBox(dias);

56 Advanced Programming with Java Chapter 1 02/21/2024


JComboBox (uneditable)
Events
 A JComboBox generates both ActionEvents (like buttons, text fields,
etc), or ItemEvents. Because it is easier to work with ActionEvents, we'll
ignore the ItemEvents. When the user chooses an item from a combo
box, an ActionEvent is generated, and the listener's actionPerformed
method is called. Use either getSelectedIndex to get the integer index
of the item that was selected, or getSelectedItem to get the value (eg,
a String) that was selected.
Example
 This example creates a JComboBox, and adds a listener to it. The
getSelectedItem method returns an Object type, so it's necessary to
downcast it back to a String.
String[] fnt = {"Serif", "SansSerif", "Monospaced"};
JComboBox fontChoice = new JComboBox(fnt);
fontChoice.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox)e.getSource();
currentFont = (String)combo.getSelectedItem();
}
});

57 Advanced Programming with Java Chapter 1 02/21/2024


JCheckBox
 A javax.swing.JCheckBox shows a small box that is
either marked or unmarked. When you click on it, it
changes from checked to unchecked or vice versa
automatically. You don't have to do any programming for
the checkbox to change.
 There are two ways to use a checkbox:
1.Active. Use addActionListener or addItemListener() so
that a method will be called whenever the checkbox is
changed.
2.Passive. Use isSelected() to test if a checkbox is
checked.

58 Advanced Programming with Java Chapter 1 02/21/2024


JCheckBox(cont)
 Common constructors and methods
 Assume JCheckBox cb; // A checkbox.
String text; // Label on text box.
boolean state; // True/false state of checkbox.
Constructors
cb = new JCheckBox(text); Creates check box, initially unchecked.
cb = new JCheckBox(text, state); Creates check box, checked or not depending on state.
Methods
state = cb.isSelected(); Returns true if the check box is checked.
cb.setSelected(state); Checks (true) or unchecks check box.
cb.addActionListener(action- Adds an action listener to the radio button. The
listener); action listener will be called if button is selected.
cb.addItemListener(item- Add an item listener to a radio button. The item
listener); listener will be called if the button is selected or
deselected.

59 Advanced Programming with Java Chapter 1 02/21/2024


JCheckBox
 Example using an ActionListener
 An ActionListener should probably be preferred to an ItemListener, and
this needs to have a little more explanation.
 Example with anonymous inner class ItemListener
 This example creates a checkbox (ignoreCase) that is already checked,
and adds it to the JPanel (content). It sets the boolean variable (ignore)
whenever the box state is changed by the user.

boolean ignore = true; // true if should ignore case . . .


JCheckBox ignoreCase = new JCheckBox("Ignore Case", true);
ignoreCase.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
// Set "ignore" whenever box is checked or unchecked.
ignore = (e.getStateChange() == ItemEvent.SELECTED);
}
}
);
content.add(ignoreCase);

60 Advanced Programming with Java Chapter 1 02/21/2024


JCheckBox
 Example checking state
 This example is similar to the above, but gets the state of
the checkbox when the value is needed.
JCheckBox ignoreCase;
. . . //... inside window constructor
JCheckBox ignoreCase = new JCheckBox("Ignore Case", true);
content.add(ignoreCase);
. . .
//... Inside processing method, eg in button listener.
if (ignoreCase.isSelected()) {
. . .

61 Advanced Programming with Java Chapter 1 02/21/2024


Radio Buttons(cont)
 Radio buttons (javax.swing.JRadioButton) are used in
groups (java.awt.ButtonGroup) where at most one can be
selected. The example below produced this image. A radio
button group starts with all buttons deselected, but after
one is selected the only way to have them appear all off is
to have an invisible button that is selected by the
program.

62 Advanced Programming with Java Chapter 1 02/21/2024


Radio Buttons(cont)
 Source code for above example
 This example creates a group of three radio buttons, puts them
in a grid layout on a panel, and puts a titled, etched border
around them.
JRadioButton yesButton = new JRadioButton("Yes" , true);
JRadioButton noButton = new JRadioButton("No" , false);
JRadioButton maybeButton = new JRadioButton("Maybe", false);
ButtonGroup bgroup = new ButtonGroup(); bgroup.add(yesButton);
bgroup.add(noButton);
bgroup.add(maybeButton);
JPanel radioPanel = new JPanel(); radioPanel.setLayout(new
GridLayout(3, 1));
radioPanel.add(yesButton);
radioPanel.add(noButton);
radioPanel.add(maybeButton);
radioPanel.setBorder(BorderFactory.createTitledBorder( BorderFac
tory.createEtchedBorder(), "Married?"));

63 Advanced Programming with Java Chapter 1 02/21/2024


Radio Buttons(cont)
Testing the status of radio buttons
 There are several ways to find out about radio button
states:
 During execution, test the radio button with isSelected().
 In the setup phase, add an action listener with
addActionListener(...). ActionListeners are called when a radio
button is selected.
 In the setup phase, add an item listener with
addItemListener. ItemListeners are called both when the
radio button is selected and (automatically) deselected.

64 Advanced Programming with Java Chapter 1 02/21/2024


Radio Buttons(cont)
 JRadioButton methods
boolean b;
JRadioButton rb = new JRadioButton("Sample", false);
 Common JRadioButton methods
b = rb.isSelected(); Returns true if that button is
selected.
rb.setSelected(b); Sets selected status of a radio
button to b (true/false).
rb.addActionListener(an-action- Adds an action listener to the radio
listener); button. The action listener will be
called if button is selected.
rb.addItemListener(an-item-listener); Add an item listener to a radio
button. The item listener will be
called if the button is selected or
65 Advanced Programming with Java Chapter 1 02/21/2024
deselected.
Radio Buttons(cont)
 ButtonGroup methods
 The most common method used for a button group is
add(), but it's also possible to get or set the selected
button. Assume:
JRadioButton rb = new JRadioButton("Sample", false); ButtonGroup
bgroup = new ButtonGroup();
 Common ButtonGroup methods
bgroup.add(rb); Adds a button to a radio button
group.
rb = bgroup.getSelectedJRadioButton(); Returns the radio button which is
currently selected.
bgroup.setSelectedJRadioButton(rb); Sets the status of a particular
radio button (unsetting others).
bgroup.add(rb); Adds a button to a radio button
group.
66 Advanced Programming with Java Chapter 1 02/21/2024
JSliders
 A slider (JSlider class) lets the user easily select from a range of
integer values. Use sliders for integer input whenever you can. They
are easier for the user than text fields, and there is no possibility of
illegal input values, so your programming is simpler.

Constructors
 The usual constructor is JSlider s = new JSlider(orientation, min,
max, initial);
orientation: JSlider.HORIZONTAL or JSlider.VERTICAL
min: The minimum value.
max: The maximum value.
initial: The initial value.
 Example:JSlider sl = new JSlider(JSlider.HORIZONTAL, 0, 20, 10);

67 Advanced Programming with Java Chapter 1 02/21/2024


Sliders(cont)
Tick Marks
 You can add both major and minor tick marks. You must
call setPaintTicks(true) to make the tick marks appear.
 Here is an example that sets major tick marks every 10
values and minor tick marks every 1 value:
sl.setMajorTickSpacing(10); // sets numbers for biggest
tick marks
sl.setMinorTickSpacing(1); // smaller tick marks
To display the values next to the major tick marks:
sl.setPaintLabels(true);

68 Advanced Programming with Java Chapter 1 02/21/2024


Menus
Types of menus
 A menu is a way to arrange buttons. There are several
types.
 Traditional dropdown menus are positioned across the top
of a window in a menu bar, and display below the menu name.
 Popup menus appear when the user clicks, eg with the right
mouse button, on a component that can handle a popup
request.
Menus and Menu Items are Buttons!
 It is easy to see how menu items are buttons that appear
when a menu appears. But the menu names in the menu
bar are also buttons. When you press on these "buttons",
they create a popup menu that you see as a dropdown
menu.
69 Advanced Programming with Java Chapter 1 02/21/2024
Menus(cont)
Dropdown menus: JMenuBar, JMenu, and JMenuItem
 A menu bar can be added to the top of a top-level
container, eg, JFrame, JApplet, or JDialog. Note that a
menu bar can not be added to JPanel.
 Dropdown menus have three parts:
1. JMenuBar is positioned across the top of a container (eg
a JFrame, JPanel, or JApplet). It's placed above the
content pane, so does not use the container's layout. Add
menus to the menubar.
2. JMenu has a name and contains a number of menu items
which are displayed is a vertical list of menu items.
3. JMenuItems and Separators are added to each menu.
Menu items are usually text "buttons", but can also have
icons, checkboxes, radio buttons, or be hierarchical
submenus.
70 Advanced Programming with Java Chapter 1 02/21/2024
Menus(cont)
Keyboard Mnemonics and Accelerators
 You can associated characters with menus and menu
items so that the user can invoke them from the
keyboard:
 Menu mnemonics can be used to open a menu by typing a
single character associated with a menu along with an
operating system defined key for this action. For
example, on MS Windows, The ALT key with F will
typically open the File menu. You can then select the
relevant menu item with either the mnemonic key for
that item, or with the arrow keys and Enter. The
corresponding letter (char) in the menu will be
underlined. For example
fileMenu.setMnemonic('F');
Advanced Programming with Java Chapter 1
71 02/21/2024
Menus(cont)
 Menu item mnemonics are used to select a menu item
when its menu is already open. Typically the character
corresponds to the first, or a significant, letter in the
menu item name. That letter in the menu item will be
underlined. openItem.setMnemonic('O');
 Accelerator key combinations are used to directly invoke
a menu item without opening the menu, for example the
common CTRL-C (Copy) execute the copy menu action.
Accelerator key options are displayed to the right of the
menu item name. Adding accelerator key requires using
KeyStroke codes. There are several ways to get these
codes, but the model below shows one of the easiest.
openItem.setAccelerator(KeyStroke.getKeyStroke("cont
rol O"));
72 Advanced Programming with Java Chapter 1 02/21/2024
JFrame frame = new JFrame();
frame.setTitle(“Menu Sample");
frame.setBounds(100, 100, 500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//menu items, then menu and finaly menubar
//menu items
JMenuItem mi1 = new JMenuItem("item 1...");
mi1.setMnemonic('I');
mi1.setAccelerator(KeyStroke.getKeyStroke("control I"));
JMenuItem mi2 = new JMenuItem("item 2");
mi2.setMnemonic('T');
mi2.setAccelerator(KeyStroke.getKeyStroke("alt T"));
JMenuItem mi3 = new JMenuItem("item 3");
mi3.setAccelerator(KeyStroke.getKeyStroke("control 3"));
JMenuItem mi4 = new JMenuItem("item 4");
mi4.setAccelerator(KeyStroke.getKeyStroke("alt 4"));
73 Advanced Programming with Java Chapter 1 02/21/2024
Menus(cont)
//menu
JMenu m1 = new JMenu("Menu 1");
m1.add(mi1);
m1.add(mi2);
JMenu m2 = new JMenu("Menu 2");
m2.add(mi3);
m2.add(mi4);
//menubar
JMenuBar mbar = new JMenuBar();
mbar.add(m1);
mbar.add(m2);

frame.setJMenuBar(mbar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
74 Advanced Programming with Java Chapter 1 02/21/2024
Dialogs
 There are several ways to build dialog boxes:
 JOptionPane - Simple Dialogs This is a very easy way
(one statement) to build simple dialogs. Usually this,
JFileChooser, and maybe JColorChooser are the only
dialog classes that you need.
 JFileChooser This will create and control a standard file
chooser dialog.
 javax.swing.JColorChooser You can call one static method
(Color.showDialog(. . .)) to display a dialog that lets the user
choose a color, or you can add listeners to make a more
complicated dialog interaction, or you can use this class to
create a color chooser pane.
 javax.swing.Jdialog This can be used for building dialogs
that are too complicated for JOptionPane.
75 Advanced Programming with Java Chapter 1 02/21/2024
Dialogs(cont)
Dialogs are attached to window (frame)
 Every dialog is attached to a window (frame). When the
window in iconified, the dialog will automatically
disappear, and it will automatically reappear when the
window is deiconified. When the window is destroyed, the
dialog will disappear.
Dialogs are usually modal
 When a dialog is active, input to other parts of the
graphical user interface will be blocked. This kind of
dialog is called a modal dialog. If you want a dialog which
is modeless (allows interaction with other windows), you
must use the JDialog class.

76 Advanced Programming with Java Chapter 1 02/21/2024


JOptionPane
 Here are two useful static methods from javax.swing.JOptionPane
that allow you to easily create dialog boxes for input and output. The
Java API documentation has many more JOptionPane options, but
these are sufficient for many uses. In the code below userInput and
text are Strings.

Use null for the component parameter if you don't have a window
 The dialog box will be centered over the component given in the first
parameter. Typically you would give the window over which it should
be centered. If your program doesn't have a window, you may simply
write null, in which case the dialog box will be centered on the
screen.

77 Advanced Programming with Java Chapter 1 02/21/2024


JOptionPane(cont)

JOptionPane.showMessageDialog(null, "Hello guys!");

78 Advanced Programming with Java Chapter 1 02/21/2024


JOptionPane(eg 1)
This line displays a String, an input text field
(JTextField), and OK and CANCEL buttons. If
the user presses the OK button, the string in
the text field is returned. If the user didn't
type anything, the string "" is returned. If the
user presses the CANCEL button, null is
returned. Because this call returns a String, it's
necessary in the next line to convert it into a
double to do the arithmetic calculation.

This line displays a String and an OK button. In


this call the String formed by concatenating a
String literal with a number. When a String is
concatenated with anything, that other operand
is converted to a String by Java, then the two
are put together into a new String.

79 Advanced Programming with Java Chapter 1 02/21/2024


JDialog (cont)
Example

Windows look and


Icon description Java look and feel
feel

question

information

warning

error

80 Advanced Programming with Java Chapter 1 02/21/2024


JFileChooser
 Use javax.swing.JFileChooser to create a file chooser
for selecting a file or directory to open or save.
To display a file chooser
 Use one of three methods to display the dialog after it
has been created.
r = fc.showOpenDialog(owner); // button labeled "Open"
r = fc.showSaveDialog(owner); // button labeled "Save"
r = fc.showDialog(owner, title);
 The owner parameter is the component (eg, JFrame,
JPanel, ...) over which the dialog should be centered. You
can use null for the owner, which will put the dialog in the
center of the screen. The title parameter is a string that
is used as the dialog's title and accept button text.

81 Advanced Programming with Java Chapter 1 02/21/2024


JFileChooser(cont)
Getting the selected file or directory
 After checking for JFileChooser.APPROVE_OPTION, the
File value of the selection is returned from a call on
getSelectedFile.

int retval = fc.showOpenDialog(null);


if (retval == JFileChooser.APPROVE_OPTION) {
File myFile = fc.getSelectedFile();
// DO YOUR PROCESSING HERE. OPEN FILE OR
...
}

82 Advanced Programming with Java Chapter 1 02/21/2024


JTabbedPane
 Description.
The JTabbedPane container allows many panels to occupy the same area
of the interface, and the user may select which to show by clicking on
a tab. A tab may also be selected by the program.
 Constructor
JTabbedPane tp = new JTabbedPane(); // Defaults to tabs along the
top edge. JTabbedPane tp = new JTabbedPane(edge);
Where edge specifies which edge the tabs are on
JTabbedPane.TOP (default)
JTabbedPane.RIGHT
JTabbedPane.BOTTOM
JTabbedPane.LEFT

83 Advanced Programming with Java Chapter 1 02/21/2024


JTabbedPane (cont)
JFrame f = new JFrame();
f.setTitle("Tab demo");
f.setSize(500,100);
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
JPanel diagramPanel = new JPanel();
JPanel sqlPanel = new JPanel();
JPanel instructionPanel = new JPanel();
JTabbedPane display = new JTabbedPane();
display.addTab("Diagram View", diagramPanel);
display.addTab("SQL View" , sqlPanel);
display.addTab("Instructions", instructionPanel);
display.setSelectedIndex(1);
f.add(display);
f.setVisible(true);
84 Advanced Programming with Java Chapter 1 02/21/2024
Anatomy of an Application
GUI
GUI Internal structure

JFrame JFrame
JPanel
containers

JPanel
JButton

JButton JLabel
JLabel

85 Advanced Programming with Java Chapter 1 02/21/2024


O n e
f P a r t
E n d o r t
x t P a
Ne n a g e r
u t M a
L a yo
86 Advanced Programming with Java Chapter 1 02/21/2024
What Is Layout?
 A layout is a set of rules that defines how graphical
components should be positioned in a container.
 Layouts tell Java where to put components in containers
(JPanel, content pane, etc). Every panel (and other
container) has a default layout, but it's better to set the
layout explicitly for clarity.
 Create a new layout object (using one of its
constructors) and use the container's setLayout method
to set the layout. Each layout has its own way to resize
components to fit the layout, and you must become
familiar with these.

87 Advanced Programming with Java Chapter 1 02/21/2024


Layout Managers
 There are many types of layout managers:
FlowLayout
GridLayout
BorderLayout
CardLayout
GridBagLayout

88 Advanced Programming with Java Chapter 1 02/21/2024


FlowLayout
As you add components to your container, it
adds them from left to right until it gets to
the end of a line, and then it starts again on
the next line.
left-to-right, row-by-row
If the container is resized, the components
will adjust themselves to new positions.
Constructors:
public FlowLayout()
public FlowLayout(int align)
public FlowLayout(int align, int hgap, int vgap)

89 Advanced Programming with Java Chapter 1 02/21/2024


GridLayout
 Is a layout manager that lays out a container’s
components in a rectangular grid with the number of
rows and columns that you specify.
 The container is divided into equal-sized rectangles,
and one component is placed in each rectangle.
 Constructors:
public GridLayout()
public GridLayout(int rows, int cols)
public GridLayout(int rows, int cols, int hgap, int vgap)

90 Advanced Programming with Java Chapter 1 02/21/2024


Border Layout
Components are placed on the container in five
distinct regions: north, south, east, west, center.
Constructor:
public BorderLayout()
public BorderLayout(int hgap, int vgap)
The containers add method can accept an
optional constraint that specifies the location
add(button, BorderLayout.CENTER);

91 Advanced Programming with Java Chapter 1 02/21/2024


BorderLayout constraints
NORTH
CENTER
SOUTH
WEST
EAST

92 Advanced Programming with Java Chapter 1 02/21/2024


CardLayout
It treats each component in the container as
an individual card.
It shows only one card at a time and the
order that the components are added to the
container is important; the first card added is
the first card displayed when the application
starts.
The layout manager maintains its own ordering
of its components and provides a mechanism to
either flip through the cards sequentially or
show a specific card.
93 Advanced Programming with Java Chapter 1 02/21/2024
CardLayout constructor
public CardLayout()
public CardLayout(int hgap, int vgap)
To add components to a CardLayout, use the
add(String, Component) method where the
String specifies an identifier for the card and
the component specifies the component to
add.
When you are ready to show the card, you can
call CardLayout class’s first, next, last, or
show methods.
94 Advanced Programming with Java Chapter 1 02/21/2024
CardLayout Methods
first( Container parent)
next(Container parent)
last(Container parent)
show(Container parent, String name)

CardLayout la = new CardLayout();


la.next(this);
la.next(this);
la.last(this);
la.show(this, “btnone”);

95 Advanced Programming with Java Chapter 1 02/21/2024


GridBagLayout
Far more advanced than any of the other
layout managers.
It is flexible layout manager that aligns
components both vertically and horizontally,
without requiring that the components be
the same size.
It maintains a dynamic grid of cells where
components can be placed and where the
components can occupy one or more of the
cells.
96 Advanced Programming with Java Chapter 1 02/21/2024
GridBagLayout constraints
 Constructor:
public GridBagLayout()
 Constraints:
 gridx, gridy - specifies the grid x and y coordinates of the 0-
based cell to place the component in. Use
GridBagConstraints.RELATIVE (default value) to place the
component in the container at the next cell following the-
previous.
 gridwidth, gridheight – specifies the number of cells the
component should occupy in the grid.
 fill – when the component’s display area (area it is given to show
itself) is larger than the control, this variable specifies how it
should fill the remaining area. Values: NONE (default) = do not
adjust the size of the components, HORIZONTAL = fill up the
width of the area only, VERTICAL = fill up the height of the area
only, and GridBagConstraints.BOTH = fill up the entire display
area.

97 Advanced Programming with Java Chapter 1 02/21/2024


Cont’d
 ipadx, ipady - specifies the component’s internal padding, or
the area outside of the component to count as part of the
size of the component.
 insets - specifies the component’s external padding, or the
minimum amount of space between the component and its
display area.
 anchor – when the component is smaller than its display
area, this variable specifies how it should be drawn in the
area: CENTER, NORTH, NORTHEAST, EAST,
SOUTHEAST, SOUTH, SOUTHWEST, WEST,
NORTHWEST.
 weightx, weighty – specifies how to distribute space
between components, important when your application is
resized. These values specify the widths and heights
relative to the other components in the frame. Note that
you must specify a weight for at least one component in a
row and a column or all components will clump together in
the center of the container.
98 Advanced Programming with Java Chapter 1 02/21/2024
Example:
GridBagLayout la = new GridBagLayout();
GridBagConstraints con=new GridBagConstraints();
setLayout(la);
con.fill = GridBagConsraints.BOTH;
add(btnone);
add(btnntwo);
con.weightx = 1.0;
la.setConstraints(btnone, con);
la.setConstraints(btntwo, con);
add(btnthree);
con.gridwidth=GridBagConstraints.REMAINDER;
la,.setConnstraints(btnthree, con);
add(btnfour);
con.gridwidth = 2;
con.gridheight = 2;
con.weighty = 1.0;
la.setConstraints(btnfour, con);

99 02/21/2024
Advanced Programming with Java Chapter 1
Cont’d
add(btnfive);
con.gridwidth = gridbagconstraints.remainder;
la.setconstraints(btnfive, con);
con.weighty = 0;
add(btnsix);
con.gridwidth = gridbagconstraints.remainser;
la.setconstraints(btnsix, con);
add(btnseven); add(btneight); add(btnnine);
con.gridwidth = 1;
con.weighty = 2.0;
la.setconstraints(btnseven, con);
la.setconstraints(btneight, con);
la.setconstraints(btnnine, con);
add(btnten);
con.gridwidth = gridbagconstraints.remainder;
la.setconstraints(btnten, con);
100 Advanced Programming with Java Chapter 1 02/21/2024
t t wo
f P a r
E n d o r t
x t P a
Ne t
E v e n

101 Advanced Programming with Java Chapter 1 02/21/2024


 At the end of this part students will be able to
 Define events and event handling
 Write code to handle events that occur in a GUI
 Determine the user action that originated the event from the event
object details
 Identify the appropriate interface for a variety of event types
 Create the appropriate event handler methods for a variety of event types
 Create inner classes and anonymous classes in event handling

102 Advanced Programming with Java Chapter 1 02/21/2024


Events -- Introduction
 In life, you encounter events that force you to suspend other
activities and respond to them immediately. .
 In Java, events represent all activities that go on between the user
and the application/program.
 Changing the state of an object is known as an event.
 Events come from User Controls

 When you define a user interface, you will usually have some way to
get user input. For example, buttons, menus, sliders, mouse
clicks, ... all generate events when the user does something with
them.
 Events can be
 Keystrokes
 mouse clicks, or Mouse moving over the component etc
103 Advanced Programming with Java Chapter 1 02/21/2024
Events Handling
 In the event handling process, there are three important players
a) Event Source
b) Event Listener/Handler
c) Event Object

104 Advanced Programming with Java Chapter 1 02/21/2024


Event Sources

A source is an object that generates an event.

occurs when the internal state of that object changes in
some way.

A source must register listeners in order for the listeners to
receive notifications about a specific type of event.

Each type of event has its own registration method. Here is
the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the
event listener. For example, the method that registers a
keyboard event listener is called addKeyListener( ). The
method that registers a mouse motion listener is called
addMouseMotionListener( ). When an event occurs, all
registered listeners are notified and receive a copy of the
event object.

105 Advanced Programming with Java Chapter 1 02/21/2024


c) Event Object
 Created when an event occurs (i.e., user interacts with a GUI
component)
 Contains all necessary information about the event that has
occurred
 Type of event that has occurred
 Source of the event
 Represented by an Event class

106 Advanced Programming with Java Chapter 1 02/21/2024


Listeners
 A listener is an object that is notified when an event occurs
 It has two major requirements
 First, it must have been registered with one or more sources to
receive notifications about specific types of events
 Second, it must implement methods to receive and process these
notifications
 The methods that receive and process events are defined in a set of
interfaces found in java.awt. event. For example, the
mouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved.

107 Advanced Programming with Java Chapter 1 02/21/2024


Types of Events
There are several kinds of events. The most common are:

108 Advanced Programming with Java Chapter 1 02/21/2024


Listeners(cont)
Common Listener Strategies
- Here are common ways to write listeners:
 Named Inner Class Listeners are one of the most common ways to
write small programs. They are convenient to write and be shared
with several components.
 Anonymous Inner Class Listeners are sometimes used to associate a
different listener with each button or other control. This is a little
quicker to write, but lacks some of the flexibility of inner class
listeners.
 Top-level Listeners (this) are commonly used where there is only one
source of an event. For example, if you are defining a subclass of
JPanel to use for drawing with a mouse, an instance of this new class
will typically also be the mouse event listener. Similarly with a JPanel
used for animation -- the panel itself may serve as the ActionListener
for the Timer. Do not use "this" as a listener for buttons, menus, etc.
because all controls must then share that one action listener.
109 Advanced Programming with Java Chapter 1 02/21/2024
Inner-class Listeners(cont)
0 Defining an inner class listener to handle events is a very popular style.

 Access. Use an inner class rather than an outer class to access


instance variables of the enclosing class. In the example below, the
myGreetingField can be referenced by the listener class. Because
simple program listeners typically get or set values of other widgets
in the interface, it is very convenient to use an inner class.
 Reuse. Unlike anonymous inner class listeners, it's easy to reuse the
same listener for more than one control, eg, the click of a button
might perform the same action as the equivalent menu item, and
might be the same as hitting the enter key in a text field.
 Organization. It's easier to group all the listeners together with
inner classes than with anonymous inner class listeners.

110 Advanced Programming with Java Chapter 1 02/21/2024


Inner-class Listeners(cont)
0 Examples: Partial source code to share one inner class listener
import javax.swing.*;
import java.awt.event.*;
class SomePanel extends JPanel {
private JButton myGreetingButton = new JButton("Hello");
private JTextField myGreetingField = new JTextField(20);
public SomePanel() { //=== Constructor
ActionListener doGreeting = new GreetingListener();
myGreetingButton.addActionListener(doGreeting);
myGreetingField.addActionListener(doGreeting);
// . . . Layout the panel.
}
/////////////////////////// Define inner class as listener.
private class GreetingListener implements ActionListener {
public void actionPerformed(ActionEvent e) {

myGreetingField.setText("Guten Tag");
}
111 Advanced Programming with Java Chapter 1 02/21/2024
}
Inner-class Listeners(cont)

JTextField inField = new JTextField(10);


...
// Create an action listener that adds the key name to a field
ActionListener keyIn = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get the name of the button
String keyNum = e.getActionCommand(); // "1", "2", ...
inField.setText(inField.getText() + keyNum);
}
};
// Create many buttons with the same listener
JButton key1 = new JButton("1");
key1.addActionListener(keyIn);
JButton key2 = new JButton("2");
key2.addActionListener(keyIn);
JButton key3 = new JButton("3");
key3.addActionListener(keyIn);
112. . . Advanced Programming with Java Chapter 1 02/21/2024
Inner-class Listeners(cont)
public class InnerDemo extends JFrame {
JButton but = new JButton("click here");
//constructor
public InnerDemo(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener actLis = new NewActLis();
but.addActionListener(actLis); When
add(but); clicked :-
pack();
setVisible(true);
}
public static void main(String[] a){
InnerDemo inner = new InnerDemo();
}
public class NewActLis implements ActionListener{
public void actionPerformed(ActionEvent a){
JOptionPane.showMessageDialog(null, "You clicked!");
}
113} Advanced Programming with Java Chapter 1 02/21/2024
}
Anonymous Listeners
A common idiom
 There is no need to define a named class simply to add a listener
object to a button. Java has a somewhat obscure syntax for creating
an anonymous innner class listener that implements an interface. For
example,
class myPanel extends JPanel {
...
public MyPanel() {
...
//in the constructor JButton b1 = new
JButton("Hello");
b1.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something for button b1
}
} );
114 Advanced Programming with Java Chapter 1 02/21/2024
……
Anonymous Listeners
Eg:
public class AnnoDemo {
public static void main(String[] a){
JButton but = new JButton("Press Me");
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
JOptionPane.showMessageDialog(null, "You pressed me");
System.out.println(“Button's clicked dude!");
}}); When
clicked :-
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(but);
f.pack();
f.setVisible(true); Console Output
}
} Button’s clicked

115 Advanced Programming with Java Chapter 1 02/21/2024


Top-level Listeners
Using this as a listener

 A common way to write simple applets is to use the applet itself


as a listener (referred to as this). For example
 This doesn't seem to be a problem for small programs, but
what happens if there is more than one button? There can be
only one actionPerformed() method in a class.

116 Advanced Programming with Java Chapter 1 02/21/2024


Top-level Listeners(cont)
public class TopLevelDemo extends JFrame implements ActionListener {
JButton but = new JButton("click here");
//constructor
public TopLevelDemo (){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
but.addActionListener(this); //
add(but);
pack();
setVisible(true);
When clicked
} :-
public void actionPerformed(ActionEvent a){
JOptionPane.showMessageDialog(null, "You clicked!");
}
public static void main(String[] a){
TopLevelDemo n = new TopLevelDemo ();
}
}
117 Advanced Programming with Java Chapter 1 02/21/2024
Top-level Listeners(cont)
Problem: One listener for many components
0 Inside the listener method, it's possible to check the parameter to
find out which component caused the event. For example,
JButton b1, b2; public void actionPerformed(ActionEvent e) {
... Object obj = e.getSource(); // get the control
that
public MyClass() { //caused the
// constructor event
... if (obj instanceof JButton) {// make sure it's a
button.
b1.addActionListener(this); JButton b = (JButton)obj;
... // downcast to a button
b2.addActionListener(this); if (b == b1) { // UGLY, DON'T DO THIS // do
something for button b1
// SAME listener! }
... else if (b == b2) {
// do something for button b2
}//end constructor
}
}
118
else1 if (o instanceof JTextField) {02/21/2024
Advanced Programming with Java Chapter
...
Top-level Listeners(cont)
public class NewClass extends JFrame implements ActionListener {
JButton but1 = new JButton("click here 1");
JButton but2 = new JButton("click here 2");
//constructor
public NewClass(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
but1.addActionListener(this);
p.add(but1);
but2.addActionListener(this);
p.add(but2);
add(p);
pack();
setVisible(true);
}

Cont…
119 Advanced Programming with Java Chapter 1 02/21/2024
Top-level Listeners(cont)
public void actionPerformed(ActionEvent a){
String whichButton = a.getActionCommand();
JOptionPane.showMessageDialog(null, "You clicked! & the button is :" +
whichButton);
}
public static void main(String[] a){
NewClass n = new NewClass();
}
}//end of class

120 Advanced Programming with Java Chapter 1 02/21/2024


(End)
Chapter 1

121 Advanced Programming with Java Chapter 1 02/21/2024

You might also like