Unit – IV
Swings
Introduction
[Link]
SAP / ICT / SOC
SASTRA
The Origins of Swing
Two Key Swing Features
Components and Containers
The Swing Packages
A Simple Swing Application
11/2/2021 1:47:47 PM CSE 208 – Java Programming 2
Introduction
¥ Build very simple user interfaces with the AWT classes.
¥ Although the AWT is still a crucial part of Java
¥ its component set is no longer widely used to create
graphical user interfaces.
¥ Today, programmers typically use Swing for this purpose.
¥ Swing is a framework that provides more powerful and flexible
GUI components than does the AWT.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 3
The Origins
of
Swing
11/2/2021 1:47:47 PM CSE 208 – Java Programming 4
The Origins of Swing
¥ Swing did not exist in the early days of Java.
¥ Rather, it was a response to deficiencies present in Java’s
original GUI subsystem: the Abstract Window Toolkit.
¥ One reason for the limited nature of the AWT is that it
translates its various visual components into their
corresponding, platform-specific equivalents, or peers.
¥ This means that the look and feel of a component is defined
by the platform, not by Java.
¥ Because the AWT components use native code resources,
they are referred to as heavyweight.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 5
The Origins of Swing
¥ The use of native peers led to several problems.
¥ First, because of variations between operating systems, a
component might look, or even act, differently on different
platforms.
¥ This potential variability threatened the overarching
philosophy of Java: write once, run anywhere.
¥ Second, the look and feel of each component was fixed
(because it is defined by the platform) and could not be
(easily) changed.
¥ Third, the use of heavyweight components caused some
frustrating restrictions.
¥ For example, a heavyweight component was always opaque.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 6
The Origins of Swing
¥ It became apparent that the limitations and restrictions present
in the AWT were sufficiently serious that a better approach
was needed.
¥ The solution was Swing.
¥ Introduced in 1997, Swing was included as part of the Java
Foundation Classes (JFC).
¥ Swing was initially available for use with Java 1.1 as a
separate library.
¥ However, beginning with Java 1.2, Swing (and the rest of the
JFC) was fully integrated into Java.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 7
Swing Is Built on the AWT
¥ It is necessary to make one important point: although Swing
eliminates a number of the limitations inherent in the AWT,
¥ Swing does not replace it.
¥ Instead, Swing is built on the foundation of the AWT.
¥ This is why the AWT is still a crucial part of Java.
¥ Swing also uses the same event handling mechanism as the
AWT.
¥ Therefore, a basic understanding of the AWT and of event
handling is required to use Swing.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 8
Two Key Swing
Features
11/2/2021 1:47:47 PM CSE 208 – Java Programming 9
Two Key Swing Features
¥ Swing Components Are Lightweight
¥ Swing components are lightweight.
¥ This means that they are written entirely in Java and do not
map directly to platform-specific peers.
¥ Lightweight components are more efficient and more flexible.
¥ Lightweight components do not translate into native peers
¥ the look and feel of each component is determined by
Swing
¥ not by the underlying operating system.
¥ As a result, each component will work in a consistent manner
across all platforms.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 10
Two Key Swing Features
¥ Swing Supports a Pluggable Look and Feel
¥ Swing supports a pluggable look and feel (PLAF).
¥ it is possible to separate the look and feel of a component
from the logic of the component.
¥ Separating out the look and feel provides a significant
advantage:
¥ it becomes possible to change the way that a component is
rendered without affecting any of its other aspects.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 11
Two Key Swing Features
¥ Swing Supports a Pluggable Look and Feel
¥ several important advantages.
¥ It is possible to define a look and feel that is consistent
across all platforms.
¥ Conversely, it is possible to create a look and feel that acts
like a specific platform.
¥ It is also possible to design a custom look and feel.
¥ Finally, the look and feel can be changed dynamically at
run time.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 12
Components
and
Containers
11/2/2021 1:47:47 PM CSE 208 – Java Programming 13
Components and Containers
¥ A Swing GUI consists of two key items:
¥ components and containers
¥ A component is an independent visual control
¥ a push button or slider.
¥ A container holds a group of components.
¥ A container is a special type of component that is designed
to hold other components.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 14
Components
¥ Swing components are derived from the JComponent class.
¥ JComponent provides the functionality that is common to all
components.
¥ JComponent inherits the AWT classes Container and
Component.
¥ A Swing component is built on and compatible with an AWT
component.
¥ All of Swing’s components are represented by classes defined
within the package [Link].
11/2/2021 1:47:47 PM CSE 208 – Java Programming 15
Hierarchy of Java Swing classes
11/2/2021 1:47:47 PM CSE 208 – Java Programming 16
Components
All component classes begin with the letter J.
For example, the class for a label is JLabel;
the class for a push button is JButton; and
the class for a scroll bar is JScrollBar.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 17
Containers
¥ Swing defines two types of containers.
¥ The first are top-level containers:
¥ JFrame, JApplet, JWindow, and JDialog.
¥ These containers do not inherit JComponent.
¥ They inherit the AWT classes Component and Container.
¥ Unlike Swing’s other components, which are lightweight, the
toplevel containers are heavyweight.
¥ This makes the top-level containers a special case in the
Swing component library.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 18
Containers
¥ The second type of containers supported by Swing are
lightweight containers.
¥ Lightweight containers do inherit JComponent.
¥ An example of a lightweight container is JPanel, which is a
general-purpose container.
¥ Lightweight containers are often used to organize and manage
groups of related components because a lightweight container
can be contained within another container.
¥ you can use lightweight containers such as JPanel to create
subgroups of related controls that are contained within an
outer container.
11/2/2021 1:47:47 PM CSE 208 – Java Programming 19
The Swing Packages
¥ Swing is a very large subsystem and makes use of many
packages
¥ Beginning the JDK 9, the Swing packages are part of the
[Link] module.
¥ The main package is [Link].
¥ This package must be imported into any program that uses
Swing.
¥ It contains the classes that implement the basic Swing
components, such as push buttons, labels, and check boxes.
11/2/2021 1:47:48 PM CSE 208 – Java Programming 20
The Swing Packages
11/2/2021 1:47:48 PM CSE 208 – Java Programming 21
A Simple Swing Application
import [Link].*;
class swingdemo
{
public static void main(String a[])
{
JFrame jf=new JFrame();
[Link]("Swing Demo");
[Link](500,500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
11/2/2021 1:47:48 PM CSE 208 – Java Programming 22
setDefaultCloseOperation()
¥ By default,
¥ when a top-level window is closed (such as when the user
clicks the close box), the window is removed from the
screen, but the application is not terminated.
¥ While this default behavior is useful in some situations
¥ it is not what is needed for most applications.
¥ Instead, you will usually want the entire application to
terminate when its top-level window is closed.
¥ The easiest way is to call setDefaultCloseOperation()
11/2/2021 1:47:48 PM CSE 208 – Java Programming 23
setDefaultCloseOperation()
¥ The general form of setDefaultCloseOperation( ) is
¥ void setDefaultCloseOperation(int what)
¥ The value passed in what determines what happens when the
window is closed.
¥ EXIT_ON_CLOSE.
¥ DISPOSE_ON_CLOSE
¥ HIDE_ON_CLOSE
¥ DO_NOTHING_ON_CLOSE
11/2/2021 1:47:48 PM CSE 208 – Java Programming 24
setDefaultCloseOperation()
• JFrame.EXIT_ON_CLOSE
• Exit the application.
• JFrame.HIDE_ON_CLOSE
• Hide the frame, but keep the application running.
• JFrame.DISPOSE_ON_CLOSE
• Dispose of the frame object, but keep the application
running.
• JFrame.DO_NOTHING_ON_CLOSE
• Ignore the click.
11/2/2021 1:47:48 PM CSE 208 – Java Programming 25
The Origins of Swing
Two Key Swing Features
Components and Containers
The Swing Packages
A Simple Swing Application
11/2/2021 1:47:48 PM CSE 208 – Java Programming 26
JLabel and ImageIcon
JTextField
JPasswordField
JTextArea
11/2/2021 1:47:48 PM CSE 208 – Java Programming 27
11/2/2021 1:47:48 PM CSE 208 – Java Programming 28
Exploring Swings - I
[Link]
SAP / ICT / SOC
SASTRA
JLabel and ImageIcon
JTextField
JPasswordField
JTextArea
11/5/2021 2:48:31 PM CSE 208 – Java Programming 2
[Link]
[Link]
[Link]
[Link]
11/5/2021 2:48:31 PM CSE 208 – Java Programming 3
Introduction
¥ Swing
¥ by presenting an overview of several Swing components,
such as buttons, check boxes, trees, and tables.
¥ The Swing components provide rich functionality and allow a
high level of customization.
¥ The purpose of this overview is to give you a feel for the
capabilities of the Swing component set.
¥ These components are all lightweight, which means that they
are all derived from JComponent.
11/5/2021 2:48:31 PM CSE 208 – Java Programming 4
JLabel and ImageIcon
JLabel is Swing’s easiest-to-use component.
It creates a label
JLabel can be used to display text and/or an icon.
It is a passive component in that it does not respond to user
input.
Jlabel constructors.
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
11/5/2021 2:48:31 PM CSE 208 – Java Programming 5
JLabel and ImageIcon
The align argument specifies the horizontal alignment of the
text and/or icon within the dimensions of the label.
It must be one of the following values:
LEFT, RIGHT, CENTER
These constants are defined in the SwingConstants interface
To obtain an icon is to use the ImageIcon class.
ImageIcon implements Icon and encapsulates an image.
An object of type ImageIcon can be passed as an argument to
the Icon parameter of JLabel’s constructor.
11/5/2021 2:48:31 PM CSE 208 – Java Programming 6
JLabel and ImageIcon
ImageIcon constructor
ImageIcon(String filename)
The icon and text associated with the label can be obtained by
the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these
methods:
void setIcon(Icon icon)
Example Program
void setText(String str)
11/5/2021 2:48:31 PM CSE 208 – Java Programming 7
11/5/2021 2:48:32 PM CSE 208 – Java Programming 8
JTextField
JTextField is the simplest Swing text component.
It is also probably its most widely used text component.
JTextField allows you to edit one line of text.
JTextField’s constructors are:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
11/5/2021 2:48:32 PM CSE 208 – Java Programming 9
JTextField
JTextField generates events in response to user interaction.
For example,
an ActionEvent is fired when the user presses enter.
A CaretEvent is fired each time the caret (i.e., the cursor)
changes position.
CaretEvent is packaged in [Link].
To obtain the text currently in the text field, call getText().
11/5/2021 2:48:32 PM CSE 208 – Java Programming 10
JTextField
String getText( )
void setText(String str)
boolean isEditable( )
void setEditable(boolean canEdit)
Example Program
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Not Supported
11/5/2021 2:48:32 PM CSE 208 – Java Programming 11
JPasswordField
11/5/2021 2:48:32 PM CSE 208 – Java Programming 12
JPasswordField
¥ The object of a JPasswordField class is a text component
specialized for password entry.
¥ It allows the editing of a single line of text.
¥ It inherits JTextField class.
¥ public class JPasswordField extends JTextField
11/5/2021 2:48:32 PM CSE 208 – Java Programming 13
JPasswordField
JPasswordField() Constructs a new JPasswordField, with a
default document, null starting text string,
and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField
with the specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized
with the specified text.
JPasswordField(String text, int columns) Construct a new JPasswordField initialized
with the specified text and columns.
Example Program
11/5/2021 2:48:32 PM CSE 208 – Java Programming 14
11/5/2021 2:48:32 PM CSE 208 – Java Programming 15
JTextArea
It represents a multi line area that displays text.
It is used to edit the text .
JTextArea inherits JComponent class.
The text in JTextArea can be set to different available fonts
and can be appended to new text .
A text area can be customized to the need of user .
11/5/2021 2:48:32 PM CSE 208 – Java Programming 16
JTextArea
JTextArea() :
constructs a new blank text area .
JTextArea(String s) :
constructs a new text area with a given initial text.
JTextArea(int row, int column) :
constructs a new text area with a given number of rows
and columns.
JTextArea(String s, int row, int column) :
constructs a new text area with a given number of rows
and columns and a given initial text.
11/5/2021 2:48:32 PM CSE 208 – Java Programming 17
JTextArea
¥ append(String s) : appends the given string to the text of the
text area.
¥ getLineCount() : get number of lines in the text of text area.
¥ setFont(Font f) : sets the font of text area to the given font.
¥ setColumns(int c) : sets the number of columns of the text
area to given integer.
¥ setRows(int r) : sets the number of rows of the text area to
given integer.
¥ getColumns() : get the number of columns of text area.
¥ getRows() : get the number of rows of text area.
Example Program
11/5/2021 2:48:32 PM CSE 208 – Java Programming 18
JLabel and ImageIcon
JTextField
JPasswordField
JTextArea
11/5/2021 2:48:32 PM CSE 208 – Java Programming 19
The Swing Buttons
JButton,
JToggleButton,
JCheckBox,
JRadioButton.
11/5/2021 2:48:32 PM CSE 208 – Java Programming 20
11/5/2021 2:48:32 PM CSE 208 – Java Programming 21
Exploring Swings - II
[Link]
SAP / ICT / SOC
SASTRA
The Swing Buttons
JButton
JToggleButton
JCheckBox
JRadioButton.
11/9/2021 2:00:46 PM CSE 208 – Java Programming 2
The Swing Buttons
Swing defines four types of buttons:
JButton, JToggleButton, JCheckBox, and JRadioButton.
AbstractButton contains methods that allow you to control the
behavior of buttons.
The following methods set these icons:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
11/9/2021 2:00:46 PM CSE 208 – Java Programming 3
The Swing Buttons
The text associated with a button can be read and written via
the following methods:
String getText( )
void setText(String str)
A button generates an action event when it is pressed.
11/9/2021 2:00:46 PM CSE 208 – Java Programming 4
JButton
When the button is pressed, an ActionEvent is generated.
The action command identifies the button.
When using two or more buttons within the same application
The action command gives you an easy way to determine
which button was pressed.
String getActionCommand()
11/9/2021 2:00:46 PM CSE 208 – Java Programming 5
JButton
The JButton class provides the functionality of a push button.
JButton allows an icon, a string, or both to be associated with
the push button.
constructors are
JButton(Icon icon) Example Program
JButton(String str)
JButton(String str, Icon icon)
11/9/2021 2:00:46 PM CSE 208 – Java Programming 6
JToggleButton
A variation on the push button is called a toggle button.
A toggle button looks just like a push button
but it acts differently
it has two states: pushed and released.
When you press a toggle button, it stays pressed rather than
popping back up as a regular push button does.
When you press the toggle button a second time, it releases
(pops up).
Each time a togglebutton is pushed, it toggles between its two
states.
11/9/2021 2:00:46 PM CSE 208 – Java Programming 7
JToggleButton
Toggle buttons are objects of the JToggleButton class.
JToggleButton implements AbstractButton.
JToggleButton is a superclass for two other Swing
components
JCheckBox
JRadioButton
JToggleButton defines the basic functionality of all two-state
components.
11/9/2021 2:00:47 PM CSE 208 – Java Programming 8
JToggleButton
Constructors
JToggleButton(String str)
creates a toggle button that contains the text passed in str.
By default, the button is in the off position
11/9/2021 2:00:47 PM CSE 208 – Java Programming 9
JToggleButton
Like JButton,
JToggleButton generates an action event each time it is
pressed.
JToggleButton also generates an item event.
When a JToggleButton is pressed in, it is selected.
When it is popped out, it is deselected.
To handle item events, you must implement the ItemListener
interface.
11/9/2021 2:00:47 PM CSE 208 – Java Programming 10
JToggleButton
Object getItem( )
A reference to the button that generated the event is
returned
boolean isSelected( )
to determine a toggle button’s state
It returns true if the button is selected and false otherwise.
Example Program
11/9/2021 2:00:47 PM CSE 208 – Java Programming 11
Check Boxes
The JCheckBox class provides the functionality of a check
box.
Its immediate superclass is JToggleButton
constructors.
JCheckBox()
JCheckBox(String str)
JCheckBox(String text, boolean selected)
11/9/2021 2:00:47 PM CSE 208 – Java Programming 12
Check Boxes
When the user selects or deselects a check box, an ItemEvent
is generated.
getItem( )
obtain a reference to the JCheckBox that generated the
event
isSelected( )
determines if the box was selected or cleared.
getText( )
method gets the text for that check box and uses it to set
the text inside the label.
Example Program
11/9/2021 2:00:47 PM CSE 208 – Java Programming 13
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in
which only one button can be selected at any one time.
They are supported by the JRadioButton class, which
extends JToggleButton.
Constructors
JRadioButton(String str)
Example Program
11/9/2021 2:00:47 PM CSE 208 – Java Programming 14
Addition GUI
11/9/2021 2:00:47 PM CSE 208 – Java Programming 15
Assignment
How to remove minimize and maximize button in jframe ?
11/9/2021 2:00:47 PM CSE 208 – Java Programming 16
The Swing Buttons
JButton,
JToggleButton,
JCheckBox,
JRadioButton.
11/9/2021 2:00:47 PM CSE 208 – Java Programming 17
JScrollPane
JList
11/9/2021 2:00:47 PM CSE 208 – Java Programming 18
11/9/2021 2:00:47 PM CSE 208 – Java Programming 19
Exploring Swings - III
[Link]
SAP / ICT / SOC
SASTRA
JScrollPane
JList
11/10/2021 5:16:22 PM CSE 208 – Java Programming 2
JScrollPane
JScrollPane is a lightweight container that automatically
handles the scrolling of another component.
The component being scrolled can be either an individual
component,
such as a table,
(or)
a group of components contained within another
lightweight container, such as a JPanel.
11/10/2021 5:16:23 PM CSE 208 – Java Programming 3
JScrollPane
In either case,
if the object being scrolled is larger than the viewable area
horizontal and/or vertical scroll bars are automatically
provided
the component can be scrolled through the pane.
Because JScrollPane automates scrolling
it usually eliminates the need to manage individual scroll
bars.
11/10/2021 5:16:23 PM CSE 208 – Java Programming 4
JScrollPane
The viewable area of a scroll pane is called the viewport.
It is a window in which the component being scrolled is
displayed.
The viewport displays the visible portion of the component
being scrolled.
The scroll bars scroll the component through the viewport.
In its default behavior, a JScrollPane will dynamically add or
remove a scroll bar as needed.
11/10/2021 5:16:23 PM CSE 208 – Java Programming 5
JScrollPane
Constructor
JScrollPane(Component comp)
The component to be scrolled is specified by comp.
Scroll bars are automatically displayed when the content of
the pane exceeds the dimensions of the viewport.
The steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the
object to scroll.
3. Add the scroll pane to the content pane.
Example Program
11/10/2021 5:16:23 PM CSE 208 – Java Programming 6
11/10/2021 5:16:23 PM CSE 208 – Java Programming 7
JList
In Swing, the basic list class is called JList.
It supports the selection of one or more items from a list.
Although the list often consists of strings, it is possible to
create a list of just about any object that can be displayed.
The items in a JList were represented as Object references.
beginning with JDK 7, JList was made generic and is now
declared like this:
class JList<E>
E represents the type of the items in the list.
11/10/2021 5:16:23 PM CSE 208 – Java Programming 8
JList
constructor
JList(E[ ] items)
This creates a JList that contains the items in the array
specified by items.
JList is based on two models.
The first is ListModel.
This interface defines how access to the list data is
achieved.
The second model is the ListSelectionModel interface
which defines methods that determine what list item or
items are selected.
11/10/2021 5:16:23 PM CSE 208 – Java Programming 9
JList
Most of the time you will wrap a JList inside a JScrollPane.
long lists will automatically be scrollable, which simplifies GUI
design.
It also makes it easy to change the number of entries in a list
without having to change the size of the JList component.
A JList generates a ListSelectionEvent when the user makes
or changes a selection.
This event is also generated when the user deselects an item.
11/10/2021 5:16:23 PM CSE 208 – Java Programming 10
JList
It is handled by implementing ListSelectionListener.
This listener specifies only one method,
called valueChanged().
void valueChanged(ListSelectionEvent le)
Both ListSelectionEvent and ListSelectionListener are
packaged in [Link].
11/10/2021 5:16:23 PM CSE 208 – Java Programming 11
JList
¥ By default,
¥ a JList allows the user to select multiple ranges of items
within the list.
¥ you can change this behavior by calling setSelectionMode().
¥ void setSelectionMode(int mode)
¥ SINGLE_SELECTION
¥ SINGLE_INTERVAL_SELECTION
¥ MULTIPLE_INTERVAL_SELECTION
11/10/2021 5:16:23 PM CSE 208 – Java Programming 12
JList
¥ obtain the index of the first item selected
¥ int getSelectedIndex()
¥ Indexing begins at zero.
¥ So, if the first item is selected, this method will return 0. If no
item is selected, –1 is returned.
¥ obtain the value associated with the selection by calling
getSelectedValue( ):
¥ E getSelectedValue()
¥ It returns a reference to the first selected value.
¥ If no value has been selected, it returns null
Example Program
11/10/2021 5:16:23 PM CSE 208 – Java Programming 13
JScrollPane
Jlist
11/10/2021 5:16:23 PM CSE 208 – Java Programming 14
JComboBox
Trees
JTable
11/10/2021 5:16:23 PM CSE 208 – Java Programming 15
11/10/2021 5:16:23 PM CSE 208 – Java Programming 16
Exploring Swings - IV
[Link]
SAP / ICT / SOC
SASTRA
JComboBox
Trees
JTable
11/12/2021 2:16:29 PM CSE 208 – Java Programming 2
References
[Link]
11/12/2021 2:16:29 PM CSE 208 – Java Programming 3
11/12/2021 2:16:29 PM CSE 208 – Java Programming 4
JComboBox
Swing provides a combo box (a combination of a text field
and a drop-down list) through the JComboBox class.
A combo box normally displays one entry
but it will also display a drop-down list that allows a user to
select a different entry.
Earlier - the items in a JComboBox were represented as
Object references.
Beginning with JDK 7, JComboBox was made generic and is
now declared like this:
class
JComboBox<E>
E represents the type of the items in the combo box.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 5
JComboBox
The JComboBox constructor:
JComboBox(E[ ] items)
items is an array that initializes the combo box.
JComboBox uses the ComboBoxModel.
Mutable combo boxes (those whose entries can be changed)
use the MutableComboBoxModel.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 6
JComboBox
In addition to passing an array of items to be displayed in the
drop-down list, items can be dynamically added to the list of
choices via the addItem( ) method.
void addItem(E obj)
Here, obj is the object to be added to the combo box.
This method must be used only with mutable combo boxes.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 7
JComboBox
JComboBox generates an action event when the user selects
an item from the list.
JComboBox also generates an item event when the state of
selection changes, which occurs when an item is selected or
deselected.
Changing a selection means that two item events will occur:
one for the deselected item and another for the selected item.
It is sufficient to simply listen for action events, but both event
types are available for your use.
Example Program1 Example Program 2
11/12/2021 2:16:29 PM CSE 208 – Java Programming 8
11/12/2021 2:16:29 PM CSE 208 – Java Programming 9
Trees
¥ A tree is a component
that presents a
hierarchical view of data.
¥ Trees are implemented
in Swing by the JTree
class.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 10
Trees
¥ A JTree has a 'root node' which is the top-most parent for all
nodes in the tree.
¥ A node is an item in a tree.
¥ A node can have many children nodes.
¥ These children nodes themselves can have further children
nodes.
¥ If a node doesn't have any children node, it is called a leaf
node.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 11
Trees
¥ The leaf node is displayed with a different visual indicator.
¥ The nodes with children are displayed with a different visual
indicator along with a visual 'handle' which can be used to
expand or collapse that node.
¥ Expanding a node displays the children and collapsing hides
them.
¥ Although JTree is packaged in [Link], its support classes
and interfaces are packaged in [Link].
¥ This is because the number of classes and interfaces needed
to support JTree is quite large.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 12
Trees
¥ constructors:
¥ JTree(Object obj [ ])
¥ JTree(Vector<?> v)
¥ JTree(TreeNode tn)
¥ In the first form,
¥ the tree is constructed from the elements in the array obj.
¥ The second form
¥ constructs the tree from the elements of vector v.
¥ In the third form,
¥ the tree whose root node is specified by tn specifies the
tree.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 13
Trees
¥ JTree relies on two models:
¥ TreeModel and
¥ TreeSelectionModel.
¥ A Jtree generates a variety of events, but three relate
specifically to trees:
¥ TreeExpansionEvent,
¥ TreeSelectionEvent, and
¥ TreeModelEvent.
¥ The tree event classes and listener interfaces are packaged in
[Link].
11/12/2021 2:16:29 PM CSE 208 – Java Programming 14
Trees
¥ TreeExpansionEvent events occur when a node is expanded
or collapsed.
¥ A TreeSelectionEvent is generated when the user selects or
deselects a node within the tree.
¥ A TreeModelEvent is fired when the data or structure of the
tree changes.
¥ The listeners for these events are
¥ TreeExpansionListener,
¥ TreeSelectionListener, and
¥ TreeModelListener.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 15
Trees
¥ To Handle TreeSelectionEvent
¥ Implement TreeSelectionListener.
¥ It defines only one method, called valueChanged( ), which
receives the TreeSelectionEvent object.
¥ You can obtain the path to the selected object by calling
getPath(), on the event object:
¥ TreePath getPath( ) Example Program
¥ It returns a TreePath object that describes the path to the
changed node.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 16
11/12/2021 2:16:29 PM CSE 208 – Java Programming 17
Example
¥ You want to display a list of employees belonging to an
organization.
¥ This should display the various attributes of employees.
¥ For example
¥ employee id, name, hourly rate, part-time status etc.
¥ The display will be more like a database table display of rows
and columns.
¥ In this case, the id,name, hourly rate are the columns.
¥ The number of rows might differ based on the number of
employees in the organization.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 18
JTable
¥ The JTable component
provided as part of the
Swing API in Java is used
to display/edit two-
dimensional data.
¥ This is similar to a
spreadsheet.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 19
JTable
¥ JTable is a component that displays rows and columns of
data.
¥ You can
¥ drag the cursor on column boundaries to resize columns.
¥ also drag a column to a new position.
¥ Depending on its configuration,
¥ it is also possible to select a row, column, or cell within the
table, and
¥ to change the data within a cell.
11/12/2021 2:16:29 PM CSE 208 – Java Programming 20
JTable
¥ JTable is conceptually simple.
¥ It is a component that consists of one or more columns of
information.
¥ At the top of each column is a heading.
¥ In addition to describing the data in a column, the heading
also provides the mechanism by which the user can change
the size of a column or change the location of a column within
the table.
¥ JTable does not provide any scrolling capabilities of its own.
¥ Instead, you will normally wrap a JTable inside a JScrollPane.
11/12/2021 2:16:30 PM CSE 208 – Java Programming 21
JTable
¥ JTable constructor.
¥ JTable(Object data[ ][ ], Object colHeads[ ])
¥ data is a two-dimensional array of the information to be presented
¥ colHeads is a one-dimensional array with the column headings.
11/12/2021 2:16:30 PM CSE 208 – Java Programming 22
JTable
¥ A JTable can generate different events.
¥ The two most fundamental events are ListSelectionEvent and
TableModelEvent.
¥ A ListSelectionEvent is generated when the user selects
something in the table.
¥ By default, JTable allows you to select one or more complete
rows, but you can change this behavior to allow one or more
columns, or one or more individual cells to be selected.
¥ A TableModelEvent is fired when that table’s data changes in
some way.
Example Program
11/12/2021 2:16:30 PM CSE 208 – Java Programming 23
JComboBox
Trees
JTable
11/12/2021 2:16:30 PM CSE 208 – Java Programming 24
Jpanel
Layout Manager
11/12/2021 2:16:30 PM CSE 208 – Java Programming 25
11/12/2021 2:16:30 PM CSE 208 – Java Programming 26
Layout Managers
[Link]
SAP / ICT / SOC
SASTRA
Jpanel
Layout Manager
11/13/2021 10:50:42 AM CSE 208 – Java Programming 2
Acknowledgement
[Link]
[Link]
[Link]
[Link]
11/13/2021 10:50:42 AM CSE 208 – Java Programming 3
JPanel
JPanel,
a part of Java Swing package
is a container that can store a group of components.
The main task of JPanel is to organize components
Various layouts can be set in JPanel which provide better
organisation of components,
It does not have a title bar.
11/13/2021 10:50:42 AM CSE 208 – Java Programming 4
JPanel
Constructor of JPanel are :
JPanel() :
creates a new panel with flow layout
JPanel(LayoutManager l) :
creates a new JPanel with specified layoutManager
Commonly used functions :
add(Component c) :
adds component to a specified container
setLayout(LayoutManager l) :
sets the layout of the container to specified layout
manager
Example Program
11/13/2021 10:50:42 AM CSE 208 – Java Programming 5
Layout Managers
11/13/2021 10:50:42 AM CSE 208 – Java Programming 6
Layout Managers – Need ?
11/13/2021 10:50:42 AM CSE 208 – Java Programming 7
Layout Managers - Need
¥ Example Programs - All of the components - have been
positioned by the FlowLayout layout manager.
¥ A layout manager automatically arranges your controls within
a window by using some type of algorithm.
¥ While it is possible to lay out Java controls by hand, you
generally won’t want to, for two main reasons.
¥ First
¥ it is very tedious to manually lay out a large number of
components.
¥ Second
¥ sometimes the width and height information is not yet
available when you need to arrange some control
11/13/2021 10:50:42 AM CSE 208 – Java Programming 8
Layout Managers
¥ Each Container object has a layout manager associated with
it.
¥ A layout manager is an instance of any class that implements
the LayoutManager interface.
¥ The layout manager is set by the setLayout() method.
¥ If no call to setLayout() is made, then the default layout
manager is used.
¥ Whenever a container is resized (or sized for the first time),
the layout manager is used to position each of the
components within it.
11/13/2021 10:50:42 AM CSE 208 – Java Programming 9
Layout Managers
¥ The setLayout( ) method has the following general form:
¥ void setLayout(LayoutManager layoutObj)
¥ Here, layoutObj is a reference to the desired layout manager.
¥ If you wish to disable the layout manager and position
components manually, pass null for layoutObj.
¥ If you do this, you will need to determine the shape and
position of each component manually, using the setBounds()
method defined by Component.
11/13/2021 10:50:42 AM CSE 208 – Java Programming 10
Layout Managers
LayoutManager is an interface that is implemented by all the classes of
layout managers.
classes that represents the layout managers:
[Link]
[Link]
[Link] [Link]
[Link]
[Link]
[Link]
[Link]
[Link] etc.
11/13/2021 10:50:42 AM CSE 208 – Java Programming 11
FlowLayout
FlowLayout implements a simple layout style, which is similar to how words
flow in a text editor.
left to right, top to bottom.
By default, components are laid out line-by-line beginning at the upper-left
corner.
when a line is filled, layout advances to the next line.
A small space is left between each component, above and below
Constructors for FlowLayout:
FlowLayout( ) – five pixels [Link]
[Link]
FlowLayout(int how)
[Link]
FlowLayout(int how, int horz, int vert)
WithoutSetBounds
11/13/2021 10:50:43 AM CSE 208 – Java Programming 12
Border Layout
¥ The BorderLayout is used to arrange the components in five
regions: north, south, east, west and center.
¥ Each region (area) may contain one component only.
¥ It is the default layout of frame or window.
¥ Constructors of BorderLayout class:
¥ BorderLayout(): creates a border layout but with no gaps
between the components.
¥ JBorderLayout(int hgap, int vgap): creates a border
layout with the given horizontal and vertical gaps between
the components.
Border Layout
11/13/2021 10:50:43 AM CSE 208 – Java Programming 13
Grid Layout
¥ The GridLayout is used to arrange the components in rectangular
grid.
¥ One component is displayed in each rectangle.
¥ Constructors of GridLayout class
¥ GridLayout(): creates a grid layout with one column per
component in a row.
¥ GridLayout(int rows, int columns): creates a grid layout with
the given rows and columns but no gaps between the
components.
¥ GridLayout(int rows, int columns, int hgap, int vgap): creates
a grid layout with the given rows and columns along with given
horizontal and vertical gaps.
GridLayout
11/13/2021 10:50:43 AM CSE 208 – Java Programming 14
setBounds()
Manually
The setBounds() method is used in such a situation to set the
position and size.
To specify the position and size of the components manually,
the layout manager of the frame can be null.
11/13/2021 10:50:43 AM CSE 208 – Java Programming 15
setBounds()
The setBounds() method needs four arguments.
The first two arguments are x and y coordinates of the top-
left corner of the component,
the third argument is the width of the component and
the fourth argument is the height of the component.
setBounds(int x-coordinate, int y-coordinate, int width, int
height)
SetBounds
11/13/2021 10:50:43 AM CSE 208 – Java Programming 16
Jpanel
Layout Manager
setbounds
11/13/2021 10:50:43 AM CSE 208 – Java Programming 17
Menus – Introduction
The Core Swing Menu Classes
JMenuBar
Constructors
Methods
11/13/2021 10:50:43 AM CSE 208 – Java Programming 18
11/13/2021 10:50:43 AM CSE 208 – Java Programming 19
Swing Menus - I
[Link]
SAP / ICT / SOC
SASTRA
Menus – Introduction
The Core Swing Menu Classes
JMenuBar
Constructors
Methods
11/16/2021 1:46:23 PM CSE 208 – Java Programming 2
Introduction
¥ Menus form an integral part of many applications because
they present the program’s functionality to the user.
¥ Because of their importance
¥ Swing provides extensive support for menus
11/16/2021 1:46:23 PM CSE 208 – Java Programming 3
Overview
¥ To create the top level menu for an application
¥ you first create a JMenuBar object.
¥ This class is a container for menus.
¥ To the JMenuBar instance
¥ you will add instances of JMenu.
¥ Each JMenu object defines a menu.
¥ Each JMenu object contains one or more selectable items.
¥ The items displayed by a JMenu are objects of JMenuItem.
¥ Thus, a JMenuItem defines a selection that can be chosen by
the user.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 4
Snapshot
Menu Bar
Menu
Menu Item
11/16/2021 1:46:23 PM CSE 208 – Java Programming 5
Overview
¥ As an alternative to menus that descend from the menu bar,
you can also create stand-alone, popup menus.
¥ To create a popup menu, first create an object of type
JPopupMenu.
¥ Then, add JMenuItems to it.
¥ A popup menu is normally activated by clicking the right
mouse button when the mouse is over a component for which
a popup menu has been defined.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 6
Overview
¥ In addition to “standard” menu items, you can also include
check boxes and radio buttons in a menu.
¥ A check box menu item is created by JCheckBoxMenuItem.
¥ A radio button menu item is created by
JRadioButtonMenuItem.
¥ Both of these classes extend JMenuItem.
¥ They can be used in standard menus and popup menus.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 7
Overview
¥ JToolBar creates a stand-alone component that is related to
the menu.
¥ It is often used to provide fast access to functionality contained
within the menus of the application.
¥ For example, a toolbar might provide fast access to the
formatting commands supported by a word processor.
¥ JSeparator is a convenience class that creates a separator
line in a menu.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 8
The Core Swing Menu Classes
11/16/2021 1:46:23 PM CSE 208 – Java Programming 9
Overview
¥ One key point to understand about Swing menus is that each
menu item extends AbstractButton.
¥ Recall that AbstractButton is also the superclass of all of
Swing’s button components, such as JButton.
¥ Thus, all menu items are,essentially, buttons.
¥ They won’t actually look like buttons when used in a menu, but
they will act like buttons.
¥ For example, selecting a menu item generates an action
event in the same way that pressing a button does.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 10
Overview
¥ Another key point is that JMenuItem is a superclass of JMenu.
¥ This allows the creation of submenus, which are, essentially,
menus within menus.
¥ To create a submenu,
¥ you first create and populate a JMenu object
¥ and then add it to another JMenu object.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 11
Overview
¥ When a menu item is selected, an action event is generated.
¥ The action command string associated with that action event
will, by default, be the name of the selection.
¥ Thus, you can determine which item was selected by
examining the action command.
¥ you can also use separate anonymous inner classes or
lambda expressions to handle each menu item’s action
events.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 12
overview
¥ Menus can also generate other types of events.
¥ For example,
¥ Each time that a menu is activated, selected, or canceled,
a MenuEvent is generated that can be listened for via a
MenuListener.
¥ Other menu-related events include
¥ MenuKeyEvent,
¥ MenuDragMouseEvent, and
¥ PopupMenuEvent.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 13
11/16/2021 1:46:23 PM CSE 208 – Java Programming 14
JMenuBar
¥ JMenuBar is essentially a container for menus.
¥ Like all components, it inherits JComponent (which inherits
Container and Component).
¥ It has only one constructor, which is the default constructor.
¥ Therefore, initially the menu bar will be empty, and you will
need to populate it with menus prior to use.
¥ Each application has one and only one menu bar.
11/16/2021 1:46:23 PM CSE 208 – Java Programming 15
JMenuBar Methods
¥ JMenuBar methods
¥ The add( ) method adds a JMenu to the menu bar.
¥ JMenu add(JMenu menu)
¥ menu is a JMenu instance that is added to the menu bar.
¥ A reference to the menu is returned.
¥ Menus are positioned in the bar from left to right, in the order
in which they are added.
11/16/2021 1:46:24 PM CSE 208 – Java Programming 16
JMenuBar Methods
¥ If you want to add a menu at a specific location, then use this
version of add(), which is inherited from Container:
¥ Component add(Component menu, int idx)
¥ Here, menu is added at the index specified by idx.
¥ Indexing begins at 0,
¥ with 0 being the left-most menu.
11/16/2021 1:46:24 PM CSE 208 – Java Programming 17
JMenuBar Methods
¥ In some cases, you might want to remove a menu that is no
longer needed.
¥ You can do this by calling remove( ), which is inherited from
Container.
¥ It has these two forms:
¥ void remove(Component menu)
¥ void remove(int idx)
¥ Menu is a reference to the menu to remove, and
¥ idx is the index of the menu to remove.
¥ Indexing begins at zero.
11/16/2021 1:46:24 PM CSE 208 – Java Programming 18
JMenuBar Methods
¥ int getMenuCount( )
¥ It returns the number of elements contained within the
menu bar.
¥ JMenuBar defines some other methods that you might find
helpful in specialized applications.
¥ For example,
¥ you can obtain an array of references to the menus in the
bar by calling getSubElements( ).
¥ You can determine if a menu is selected by calling
isSelected( ).
11/16/2021 1:46:24 PM CSE 208 – Java Programming 19
JMenuBar
¥ Once a menu bar has been created and populated, it is added
to a JFrame by calling setJMenuBar( ) on the JFrame
instance. (Menu bars are not added to the content pane.)
¥ The setJMenuBar( ) method is shown here:
¥ void setJMenuBar(JMenuBar mb)
¥ Here, mb is a reference to the menu bar.
¥ The menu bar will be displayed in a position determined by
the look and feel.
¥ Usually, this is at the top of the window.
11/16/2021 1:46:24 PM CSE 208 – Java Programming 20
11/16/2021 1:46:24 PM CSE 208 – Java Programming 21
The Core Swing Menu Classes
JMenuBar
Constructors
Methods
11/16/2021 1:46:24 PM CSE 208 – Java Programming 22
JMenu
¥ Constructors
¥ Methods
¥ JMenuItem
¥ Add Tooltips to Menu Items
¥ JCheckBoxMenuItem
¥ JRadioButtonMenuItem
11/16/2021 1:46:24 PM CSE 208 – Java Programming 23
11/16/2021 1:46:24 PM CSE 208 – Java Programming 24
Swing Menus - II
[Link]
SAP / ICT / SOC
SASTRA
JMenu
Constructors
Methods
JMenuItem
Add Tooltips to Menu Items
JCheckBoxMenuItem
JRadioButtonMenuItem
11/17/2021 5:11:35 PM CSE 208 – Java Programming 2
JMenu
JMenu encapsulates a menu, which is populated with
JMenuItems.
It is derived from JMenuItem.
This means that one JMenu can be a selection in another
JMenu.
This enables one menu to be a submenu of another.
11/17/2021 5:11:35 PM CSE 208 – Java Programming 3
JMenu Constructors
JMenu constructors.
JMenu(String name)
This constructor creates a menu that has the title specified
by name.
To create an unnamed menu,
you can use the default constructor:
JMenu()
The menu is empty until menu items are added to it.
11/17/2021 5:11:35 PM CSE 208 – Java Programming 4
JMenu Methods
JMenu defines many methods
To add an item to the menu, use the add( ) method
JMenuItem add(JMenuItem item)
Component add(Component item, int idx)
Item is the menu item to add.
The first form adds the item to the end of the menu.
The second form adds the item at the index specified by idx.
Indexing starts at zero.
Both forms return a reference to the item added.
you can also use insert( ) to add menu items to a menu.
11/17/2021 5:11:35 PM CSE 208 – Java Programming 5
JMenu Methods
Add a separator (an object of type JSeparator) to a menu by
addSeparator( ).
void addSeparator()
The separator is added onto the end of the menu.
Insert a separator into a menu by insertSeparator( )
void insertSeparator(int idx)
idx specifies the zero-based index at which the
separator will be added.
11/17/2021 5:11:35 PM CSE 208 – Java Programming 6
JMenu Methods
Remove an item from a menu using remove( ).
void remove(JMenuItem menu)
void remove(int idx)
Menu is a reference to the item to remove and idx is the index
of the item to remove.
To obtain the number of items in the menu – use -
getMenuComponentCount( )
int getMenuComponentCount( )
To get an array of the items in the menu – use -
getMenuComponents( )
Component[ ] getMenuComponents( )
11/17/2021 5:11:35 PM CSE 208 – Java Programming 7
11/17/2021 5:11:35 PM CSE 208 – Java Programming 8
JMenuItem
JMenuItem encapsulates an element in a menu.
This element can be
a selection linked to some program action
such as Save or Close
(or) it can cause a submenu to be displayed.
JMenuItem is derived from AbstractButton, and every item in a
menu can be thought of as a special kind of button.
When a menu item is selected
an action event is generated.
11/17/2021 5:11:35 PM CSE 208 – Java Programming 9
JMenuItem Constructors
JMenuItem constructors.
JMenuItem(String name)
JMenuItem(Icon image)
JMenuItem(String name, Icon image)
JMenuItem(String name, int mnem)
JMenuItem(Action action)
11/17/2021 5:11:35 PM CSE 208 – Java Programming 10
JMenuItem
Because menu items inherit AbstractButton, you have access
to the functionality provided by AbstractButton.
One such method that is often useful with menus is
setEnabled( ), which you can use to enable or disable a menu
item.
It is shown here:
void setEnabled(boolean enable)
If enable is true, the menu item is enabled.
If enable is false, the item is disabled and cannot be selected.
11/17/2021 5:11:35 PM CSE 208 – Java Programming 11
Add Tooltips to Menu Items
A tooltip is a small message that describes an item.
It is automatically displayed if the mouse remains over the
item for a moment.
You can add a tooltip to a menu item by calling
setToolTipText() on the item, specifying the text you want
displayed.
void setToolTipText(String msg)
msg is the string that will be displayed when the tooltip is
activated.
11/17/2021 5:11:36 PM CSE 208 – Java Programming 12
JCheckBoxMenuItem
Swing makes it easy to use check boxes in menus
To add a check box to a menu,
Create a JCheckBoxMenuItem.
constructors.
JCheckBoxMenuItem(String name)
The initial state of the check box is unchecked
JCheckBoxMenuItem(String name, boolean state)
if state is true, the box is initially checked
JCheckBoxMenuItem(String name, Icon icon)
name specifies the name of the item and the image
associated with the item is passed in icon
11/17/2021 5:11:36 PM CSE 208 – Java Programming 13
JRadioButtonMenuItem
A radio button can be added to a menu by creating an object
of type JRadioButtonMenuItem
constructors.
JRadioButtonMenuItem(String name)
JRadioButtonMenuItem(String name, boolean state)
JRadioButtonMenuItem(String name, Icon icon, boolean
state)
11/17/2021 5:11:36 PM CSE 208 – Java Programming 14
SubMenu Demo Program
Shape Demo Program
11/17/2021 5:11:36 PM CSE 208 – Java Programming 15
JMenu
Constructors
Methods
JMenuItem
Add Tooltips to Menu Items
JCheckBoxMenuItem
JRadioButtonMenuItem
11/17/2021 5:11:36 PM CSE 208 – Java Programming 16
Popup Menu
11/17/2021 5:11:36 PM CSE 208 – Java Programming 17
11/17/2021 5:11:36 PM CSE 208 – Java Programming 18
Swing Menus - III
[Link]
SAP / ICT / SOC
SASTRA
Add Mnemonics and Accelerators to Menu Items
Popup Menu
11/19/2021 2:12:32 PM CSE 208 – Java Programming 2
Add Mnemonics to Menu Items
In real applications, a menu usually includes support for
keyboard shortcuts because they give an experienced user
the ability to select menu items rapidly.
Keyboard shortcuts come in two forms:
mnemonics and accelerators.
A mnemonic
defines a key that lets you select an item from an active
menu by typing the key.
An accelerator
is a key that lets you select a menu item without having to
first activate the menu.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 3
Add Mnemonics to Menu Items
A mnemonic can be specified
for both JMenuItem and JMenu objects.
There are two ways to set the mnemonic for JMenuItem.
First
It can be specified when an object is constructed using this
constructor:
JMenuItem(String name, int mnem)
the name is passed in name and the mnemonic is passed
in mnen.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 4
Add Mnemonics and Accelerators to Menu Items
Second, you can set the mnemonic by calling setMnemonic().
To specify a mnemonic for JMenu, you must call
setMnemonic( ).
void setMnemonic(int mnem)
mnem specifies the mnemonic.
It should be one of the constants defined in
[Link],
such as KeyEvent.VK_F or KeyEvent.VK_Z.
Mnemonics are not case sensitive
so in the case of VK_A, typing either a or A will work.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 5
Add Mnemonics to Menu Items
By default,
the first matching letter in the menu item will be
underscored.
In cases in which you want to underscore a letter other than
the first match,
specify the index of the letter as an argument to
setDisplayedMnemonicIndex(),
which is inherited by both JMenu and JMenuItem from
AbstractButton.
void setDisplayedMnemonicIndex(int idx)
The index of the letter to underscore is specified by idx.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 6
Add Accelerators to Menu Items
An accelerator can be associated with a JMenuItem object.
It is specified by calling setAccelerator( ).
void setAccelerator(KeyStroke ks)
ks is the key combination that is pressed to select the
menu item.
KeyStroke is a class that contains several factory methods
that construct various types of keystroke accelerators
static KeyStroke getKeyStroke(char ch)
static KeyStroke getKeyStroke(Character ch, int modifier)
static KeyStroke getKeyStroke(int ch, int modifier)
11/19/2021 2:12:33 PM CSE 208 – Java Programming 7
Add Mnemonics and Accelerators to
Menu Items
Here, ch specifies the accelerator character.
In the first version, the character is specified as a char value.
In the second, it is specified as an object of type Character.
In the third, it is a value of type KeyEvent.
The value of modifier must be one or more of the following constants,
defined in the [Link] class.
If you pass VK_A for the key character and
InputEvent.CTRL_DOWN_MASK for the modifier, the accelerator key
combination is CTRL-A.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 8
MenuwithMnemonics Demo
11/19/2021 2:12:33 PM CSE 208 – Java Programming 9
Creating a Popup Menu
A popup menu is activated by clicking the right mouse button
when over a component.
Popup menus are supported in Swing by the JPopupMenu
class.
JPopupMenu has two constructors.
JPopupMenu()
It creates a default popup menu.
The other constructor lets you specify a title for the menu.
Whether this title is displayed is subject to the look and feel.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 10
JPopupMenu - Activation Process
Popup menus are constructed like regular menus.
First, create a JPopupMenu object, and then add menu items to it.
Menu item selections are also handled in the same way: by listening for
action events.
The main difference between a popup menu and regular menu is the
activation process.
Activating a popup menu requires three steps:
1. You must register a listener for mouse events.
2. Inside the mouse event handler, you must watch for the popup
trigger.
3. When a popup trigger is received, you must show the popup menu
by calling show().
11/19/2021 2:12:33 PM CSE 208 – Java Programming 11
JPopupMenu - Activation Process
A popup menu is normally activated by clicking the right
mouse button when the mouse pointer is over a component
for which a popup menu is defined.
Thus, the popup trigger is usually caused by right-clicking the
mouse on a popup menu–enabled component.
To listen for the popup trigger, implement the MouseListener
interface and then register the listener by calling the
addMouseListener() method.
MouseListener defines the methods :
mousePressed() and mouseReleased().
mouseEntered() and mouseExited().
mouseClicked() .
11/19/2021 2:12:33 PM CSE 208 – Java Programming 12
MouseListener - Methods
Of these, two are very important relative to the popup menu:
mousePressed( ) and mouseReleased( ).
Depending on the installed look and feel, either of these two
events can trigger a popup menu.
For this reason,
It is often easier to use a MouseAdapter to implement the
MouseListener interface and simply override
mousePressed( ) and mouseReleased( ).
11/19/2021 2:12:33 PM CSE 208 – Java Programming 13
MouseEvent class - Methods
The MouseEvent class defines several methods, but only
four are commonly needed when activating a popup menu.
They are shown here:
int getX( )
int getY( )
boolean isPopupTrigger( )
Component getComponent( )
11/19/2021 2:12:33 PM CSE 208 – Java Programming 14
MouseEvent class - Methods
The current X,Y location of the mouse relative to the source of
the event is found by calling getX( ) and getY( ).
These are used to specify the upper-left corner of the
popup menu when it is displayed.
The isPopupTrigger( ) method returns true if the mouse
event represents a popup trigger and false otherwise.
You will use this method to determine when to pop up the
menu.
To obtain a reference to the component that generated the
mouse event, call getComponent( ).
11/19/2021 2:12:33 PM CSE 208 – Java Programming 15
JPopupMenu
To actually display the popup menu, call the show( ) method
defined by JPopupMenu.
void show(Component invoker, int upperX, int upperY)
invoker is the component relative to which the menu will be
displayed.
The values of upperX and upperY define the X,Y location of
the upper-left corner of the menu, relative to invoker.
A common way to obtain the invoker
is to call getComponent() on the event object passed to
the mouse event handler.
11/19/2021 2:12:33 PM CSE 208 – Java Programming 16
Popupmenu Demo Program
11/19/2021 2:12:33 PM CSE 208 – Java Programming 17
Add Mnemonics to Menu Items
Add Accelerators to Menu Items
Create a Popup Menu
11/19/2021 2:12:33 PM CSE 208 – Java Programming 18
Create a ToolBar
11/19/2021 2:12:34 PM CSE 208 – Java Programming 19
11/19/2021 2:12:34 PM CSE 208 – Java Programming 20
Swing Menus - IV
[Link]
SAP / ICT / SOC
SASTRA
Create a ToolBar
11/20/2021 10:34:58 AM CSE 208 – Java Programming 2
Toolbar
A toolbar is a component that can serve as an alternative to a
menu.
A toolbar contains a list of buttons (or other components) that
give the user immediate access to various program options.
For example
a toolbar might contain buttons that select various font
options, such as bold, italics, highlight, or underline.
These options can be selected without needing to drop
through a menu.
11/20/2021 10:34:58 AM CSE 208 – Java Programming 3
Toolbar
Typically,
Toolbar buttons show icons rather than text, although
either or both are allowed
Furthermore,
Tooltips are often associated with icon-based toolbar
buttons.
Toolbars can be positioned on any side of a window by
dragging the toolbar, or they can be dragged out of the
window entirely, in which case they become free floating.
11/20/2021 10:34:58 AM CSE 208 – Java Programming 4
Toolbar
In Swing, toolbars are instances of the JToolBar class.
Its constructors enable you to create a toolbar with or without
a title.
You can also specify the layout of the toolbar, which will be
either horizontal or vertical.
JToolBar constructors:
JToolBar()
JToolBar(String title)
JToolBar(int how)
[Link] or [Link].
JToolBar(String title, int how)
11/20/2021 10:34:58 AM CSE 208 – Java Programming 5
Toolbar
A toolbar is typically used with a window that uses a border layout.
Reasons.
First, it allows the toolbar to be initially positioned along one of the four
border positions.
Frequently, the top position is used.
Second, it allows the toolbar to be dragged to any side of the window.
In addition to dragging the toolbar to different locations within a window,
you can also drag it out of the window.
Doing so creates an undocked toolbar.
If you specify a title when you create the toolbar, then that title will be
shown when the toolbar is undocked.
11/20/2021 10:34:58 AM CSE 208 – Java Programming 6
Toolbar
Add buttons (or other components) to a toolbar in much the
same way that you add them to a menu bar.
Simply call add( ).
The components are shown in the toolbar in the order in which
they are added.
Once you have created a toolbar
do not add it to the menu bar
add it to the window container.
11/20/2021 10:34:58 AM CSE 208 – Java Programming 7
Toolbar
As mentioned, typically you will add a toolbar to the top (that
is, north) position of a border layout, using a horizontal
orientation.
The component that will be affected is added to the center of
the border layout.
Using this approach causes the program to begin running with
the toolbar in the expected location.
11/20/2021 10:34:58 AM CSE 208 – Java Programming 8
Toolbar Demo Program
11/20/2021 10:34:58 AM CSE 208 – Java Programming 9
Create a ToolBar
11/20/2021 10:34:58 AM CSE 208 – Java Programming 10
Use Actions
11/20/2021 10:34:59 AM CSE 208 – Java Programming 11
11/20/2021 10:34:59 AM CSE 208 – Java Programming 12
Swing Menus - IV
[Link]
SAP / ICT / SOC
SASTRA
Use Actions
11/23/2021 1:41:22 PM CSE 208 – Java Programming 2
Use Actions
Often, a toolbar and a menu item contain items in common.
For example,
The same functions provided by the Debug toolbar might
also be offered through a menu selection.
In such a case,
selecting an option (such as setting a breakpoint)
causes the same action to occur,
independently of whether the menu or the toolbar was
used.
11/23/2021 1:41:22 PM CSE 208 – Java Programming 3
Debug Tool bar
11/23/2021 1:41:22 PM CSE 208 – Java Programming 4
Menu – Debug options
11/23/2021 1:41:23 PM CSE 208 – Java Programming 5
Use Actions
Both the toolbar button and the menu item would (most likely)
use the same icon.
Furthermore,
when a toolbar button is disabled
the corresponding menu item would also need to be
disabled.
Such a situation would normally lead to a fair amount of
duplicated, interdependent code, which is less than optimal.
Swing provides a solution: the action.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 6
Use Actions
An action is an instance of the Action interface.
Action extends the ActionListener interface and provides a
means of combining state information with the
actionPerformed() event handler.
This combination allows one action to manage two or more
components.
For example, an action lets you centralize the control and
handling of a toolbar button and a menu item.
Instead of having to duplicate code, your program need only
create an action that automatically handles both components.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 7
Use Actions
Because Action extends ActionListener, an action must
provide an implementation of the actionPerformed() method.
This handler will process the action events generated by the
objects linked to the action.
Action defines several methods of its own.
putValue() - It sets the value of the various properties
associated with an action.
void putValue(String key, Object val)
It assigns val to the property specified by key that represents
the desired property.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 8
Use Actions
getValue( ) - method that obtains a specified Property.
Object getValue(String key)
It returns a reference to the property specified by key.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 9
Use Actions
Swing provides a partial implementation called AbstractAction
that you can extend.
By extending AbstractAction
you need implement only one method: actionPerformed( ).
AbstractAction provides three constructors.
AbstractAction(String name, Icon image)
It constructs an AbstractAction that has the name specified by
name and the icon specified by image.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 10
Use Actions
Once you have created an action,
it can be added to a JToolBar and used to construct a
JMenuItem.
To add an action to a JToolBar, use this version of add( ):
JButton add(Action actObj)
Here, actObj is the action that is being added to the toolbar.
The properties defined by actObj are used to create a toolbar
button.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 11
Use Actions
To create a menu item from an action, use this JMenuItem
constructor:
JMenuItem(Action actObj)
Here, actObj is the action used to construct a menu item
according to its properties.
In addition to JToolBar and JMenuItem, actions are also
supported by several other Swing components, such as
JPopupMenu, JButton, JRadioButton, and JCheckBox.
JRadioButtonMenuItem and JCheckBoxMenuItem also
support actions.
11/23/2021 1:41:23 PM CSE 208 – Java Programming 12
Thanks to [Link] Madam
[Link]
11/23/2021 1:41:23 PM CSE 208 – Java Programming 13
Use Actions
11/23/2021 1:41:23 PM CSE 208 – Java Programming 14
11/23/2021 1:41:23 PM CSE 208 – Java Programming 15
11/23/2021 1:41:23 PM CSE 208 – Java Programming 16
Graphics & Fonts
[Link]
SAP / ICT / SOC
SASTRA
Working with
Graphics
Colors
Fonts
11/24/2021 7:07:15 PM CSE 208 – Java Programming 2
Introducing Graphics
The Graphics class defines a number of methods that draw
various types of objects, such as lines, rectangles, and arcs.
Objects can be drawn edge-only or filled.
Objects are drawn and filled in the currently selected color,
which is black by default.
When a graphics object is drawn that exceeds the dimensions
of the window, output is automatically clipped.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 3
Drawing Lines
Lines are drawn by means of the drawLine( ) method.
void drawLine(int startX, int startY, int endX, int endY )
drawLine( ) displays a line in the current drawing color that
begins at startX, startY and ends at endX, endY.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 4
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined
and filled rectangle, respectively.
void drawRect(int left, int top, int width, int height)
void fillRect(int left, int top, int width, int height)
The upper-left corner of the rectangle is at left, top.
The dimensions of the rectangle are specified by width and
height.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 5
Drawing Rectangles
To draw a rounded rectangle, use drawRoundRect( ) or
fillRoundRect( ).
void drawRoundRect(int left, int top, int width, int height,
int xDiam, int yDiam)
void fillRoundRect(int left, int top, int width, int height,
int xDiam, int yDiam)
A rounded rectangle has rounded corners.
The diameter of the rounding arc along the X axis is specified
by xDiam.
The diameter of the rounding arc along the Y axis is specified
by yDiam.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 6
Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ).
To fill an ellipse, use fillOval( ).
void drawOval(int left, int top, int width, int height)
void fillOval(int left, int top, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-
left corner is specified by left, top and whose width and height
are specified by width and height.
To draw a circle, specify a square as the bounding rectangle.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 7
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ).
void drawArc(int left, int top, int width, int height, int
startAngle, int sweepAngle)
void fillArc(int left, int top, int width, int height, int
startAngle, int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner
is specified by left,top and whose width and height are
specified by width and height.
The arc is drawn from startAngle through the angular distance
specified by sweepAngle.
Angles are specified in degrees.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 8
Drawing Polygons
It is possible to draw arbitrarily shaped figures using
drawPolygon( ) and fillPolygon( ).
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon’s endpoints are specified by the coordinate pairs
contained within the x and y arrays.
The number of points defined by these arrays is specified by
numPoints.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 9
Working with Color
Java supports color in a portable, device-independent fashion.
The AWT color system allows you to specify any color you
want.
It then finds the best match for that color, given the limits of
the display hardware currently executing your program.
Color is encapsulated by the Color class.
Color defines several constants (for example,[Link]) to
specify a number of common colors.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 10
Working with Color
You can also create your own colors, using one of the Color
constructors.
Color(int red, int green, int blue)
Color Methods
int getRed( )
int getGreen( )
int getBlue( )
void setColor(Color newColor)
Color getColor( )
Example Program
11/24/2021 7:07:16 PM CSE 208 – Java Programming 11
Working with Fonts
The AWT supports multiple type fonts.
Fonts have a family name, a logical font name, and a face
name.
The family name is the general name of the font, such as
Courier.
The logical name specifies a name, such as Monospaced, that
is linked to an actual font at runtime.
The face name specifies a specific font, such as Courier Italic.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 12
Working with Fonts
Font(String fontName, int fontStyle, int pointSize)
fontName specifies the name of the desired font.
All Java environments will support the following fonts:
Dialog, DialogInput, SansSerif, Serif, and Monospaced.
Dialog is also the default if you don’t explicitly set a font.
The style of the font is specified by fontStyle.
It may consist of one or more of these three constants:
[Link], [Link], and [Link].
To combine styles, OR them together.
For example, [Link] | [Link] specifies a bold,
italics style.
The size, in points, of the font is specified by pointSize.
11/24/2021 7:07:16 PM CSE 208 – Java Programming 13
Working with Fonts
void setFont(Font fontObj)
Font getFont( ) Example Program
String[ ] getAvailableFontFamilyNames( )
Font getFont( )
These methods are members of GraphicsEnvironment
you need a GraphicsEnvironment reference to call them.
You can obtain this reference by using the
getLocalGraphicsEnvironment( ) static method, which is defined by
GraphicsEnvironment.
static GraphicsEnvironment getLocalGraphicsEnvironment( )
11/24/2021 7:07:16 PM CSE 208 – Java Programming 14
Working with
Graphics
Colors
Fonts
11/24/2021 7:07:16 PM CSE 208 – Java Programming 15
11/24/2021 7:07:17 PM CSE 208 – Java Programming 16
11/24/2021 7:07:17 PM CSE 208 – Java Programming 17
Layout Managers - 2
[Link]
SAP / ICT / SOC
SASTRA
Layout Manager
CardLayout
GridbagLayout
11/26/2021 1:54:56 PM CSE 208 – Java Programming 2
Recap
¥ FlowLayout
¥ BorderLayout
¥ GridLayout
¥ setBounds
11/26/2021 1:54:57 PM CSE 208 – Java Programming 3
Using Insets
¥ Sometimes you want to leave a small amount of space
between the container that holds your components and the
window that contains it.
¥ To do this
¥ override the getInsets() method that is defined by
Container.
¥ This method returns an Insets object that contains the top,
bottom, left, and right inset to be used when the container is
displayed.
¥ These values are used by the layout manager to inset the
components when it lays out the window.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 4
Using Insets
¥ The constructor for Insets is shown here:
¥ Insets(int top, int left, int bottom, int right)
¥ The values passed in top, left, bottom, and right specify the
amount of space between the container and its enclosing
window.
¥ The getInsets( ) method has this general form:
¥ Insets getInsets( )
¥ When overriding this method
¥ you must return a new Insets object that contains the inset
spacing you desire.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 5
CardLayout
The class CardLayout arranges each component in the
container as a card.
Only one card is visible at a time, and the container acts as a
stack of cards.
CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
11/26/2021 1:54:57 PM CSE 208 – Java Programming 6
CardLayout
The cards are typically held in an object of type Panel.
This panel must have CardLayout selected as its layout
manager.
The cards that form the deck are also typically objects of type
Panel.
Thus, you must create a panel that contains the deck and a
panel for each card in the deck.
Next, you add to the appropriate panel the components that
form each card.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 7
CardLayout
You then add these panels to the panel for which CardLayout
is the layout manager.
Finally, you add this panel to the window.
Once these steps are complete, you must provide some way
for the user to select between cards.
One common approach is to include one push button for each
card in the deck.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 8
CardLayout
void add(Component panelRef, Object name)
name is a string that specifies the name of the card whose
panel is specified by panelRef.
After you have created a deck, your program activates a card
by calling one of the following methods defined by
CardLayout:
void first(Container deck) Example
void last(Container deck)
void next(Container deck)
void previous(Container deck)
deck is a reference to the container (usually a panel) that
holds the cards,
11/26/2021 1:54:57 PM CSE 208 – Java Programming 9
GridBagLayout
Some situations will require that you take a bit more control
over how the components are arranged
use a grid bag layout, which is specified by the GridBagLayout
class.
You can specify the relative placement of components by
specifying their positions within cells inside a grid.
The key to the grid bag is that each component can be a
different size, and each row in the grid can have a different
number of columns.
This is why the layout is called a grid bag.
It’s a collection of small grids joined together.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 10
GridBagLayout
The location and size of each component in a grid bag are
determined by a set of constraints linked to it.
The constraints are contained in an object of type
GridBagConstraints.
Constraints include
the height and width of a cell,
the placement of a component,
its alignment, and its anchor point within the cell.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 11
GridBagLayout
The general procedure for using a grid bag is to first create a
new GridBagLayout object and to make it the current layout
manager.
Then, set the constraints that apply to each component that
will be added to the grid bag.
Finally, add the components to the layout manager.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 12
GridBagLayout
GridBagLayout defines only one constructor.
GridBagLayout( )
setConstraints( ).
void setConstraints(Component comp, GridBagConstraints
cons)
Here, comp is the component for which the constraints
specified by cons apply.
This method sets the constraints that apply to each
component in the grid bag.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 13
GridBagLayout
The key to successfully using GridBagLayout is the proper
setting of the constraints, which are stored in a
GridBagConstraints object.
GridBagConstraints defines several fields that you can set to
govern the size, placement, and spacing of a component.
11/26/2021 1:54:57 PM CSE 208 – Java Programming 14
GridBagLayout
int gridwidth
Specifies the width of the component in terms of cells.
Default is 1
To specify that a component use the remaining space in a
row, use [Link].
To specify that a component use the next-to-last cell in a row,
use [Link].
int gridheight
Specifies the height of the component in terms of cells.
Default is 1
11/26/2021 1:54:57 PM CSE 208 – Java Programming 15
GridBagLayout
You can specify a padding value that will be used to increase
the minimum size of a cell.
To pad horizontally, assign a value to ipadx.
To pad vertically,assign a value to ipady.
Example
11/26/2021 1:54:57 PM CSE 208 – Java Programming 16
Layout Manager
CardLayout
GridbagLayout
11/26/2021 1:54:57 PM CSE 208 – Java Programming 17
11/26/2021 1:54:57 PM CSE 208 – Java Programming 18
11/26/2021 1:54:58 PM CSE 208 – Java Programming 19