Unit-IV JAVA Swing
Unit-IV JAVA Swing
ELECTIVE-I B
OBJECT ORIENTED PROGRAMMING
(PCO-504E)
V SEMESTER 2022-23
DIPLOMA IN COMPUTER/ELECTRONICS ENGINEERING
◼ Part of the Java Foundation Classes (JFC) that is used to create window-
based graphical user interface (GUI) applications.
◼ A set of classes that provides powerful and flexible GUI components
◼ A rich set of built-in controls. Trees, image buttons, tabbed panes, sliders,
toolbars, etc.
◼ Controls are platform-independent and lightweight - Not built on native
window-system windows
◼ More customizable. Can change border, text alignment, or add image to
almost any control. Can customize how minor features are drawn.
◼ "Pluggable" look and feel. Can change look and feel at runtime, or design
own look and feel.
4
SWING PACKAGES
Javax.swing.tree Javax.swing.undo
5
HIERARCHY OF JAVA SWING CLASSES
A SIMPLE SWING APPLICATION
• A Simple Swing application uses two Swing components: JFrame and JLabel.
• JFrame is the top-level container that is commonly used for Swing applications.
• JLabel is the Swing component that creates a label, which is a component that displays
information.
• The program uses a JFrame container to hold an instance of a JLabel. The label displays a
short text message.
EXPECTED OUTPUT
A SIMPLE SWING APPLICATION
import javax.swing.*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
9
A SIMPLE SWING APPLICATION
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater( new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}
10
HANDLE AN EVENT IN A SWING PROGRAM
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
13
LAYOUT HEURISTICS
FlowLayout GridLayout
Left to right,
Top to bottom
14
s
EVENT HANDLING IN A SWING PROGRAM
• The event handling mechanism used by Swing is the “Delegation Event Model”.
• In this program we handles the event generated by a Swing push button (JButton)
• It uses four Swing components: A top level JFrame container, two push buttons (JButton), one
label JLabel.
• The JFrame container holds two instances of JButton push buttons named Alpha and Beta,
and an instance of a JLabel. The label initially displays a text message ‘Press a Button’.
• Each time a push button is pressed the string displayed in the label is changed to reflect
which button was pressed
• Sample output is shown below.
SWING APPLET
• It uses four Swing components: A top level JApplet container, two push buttons
(JButton), one label JLabel.
• The Swing JApplet container holds two instances of JButton push buttons named Alpha
and Beta, and an instance of a JLabel. The label initially displays a text message ‘Press a
Button’.
• Each time a push button is pressed the string displayed in the label is changed to reflect
which button was pressed
• Sample output is shown below.
A SIMPLE SWING-BASED APPLET
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
◼ JLable(String str)
Methods
◼ Icon getIcon()
◼ String getText()
20
JLABLE AND IMAGEICON EXAMPLE
import java.awt.*;
import javax.swing.*;
22
JLABEL AND IMAGEICON
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
23
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.
• Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
• Here, str is the string to be initially presented, and cols is the number of columns in the
text field. If no string is specified, the text field is initially empty. If the number of
columns is not specified, the text field is sized to fit the specified string
JTEXTFIELD
◼ JTextField(String str)
Methods
◼ String getText()
28
JTEXTFIELD
private void makeGUI() {
29
SWING BUTTONS
31
JBUTTON
35
JTOGGLEBUTTON
• When you press the toggle button it stays pressed, when you press a second time it releases
• Therefore, each time a toggle button is pushed, it toggles between its two states.
• By default the button is in the off position
• JToggleButton is super class of JCheckBox and JRadioButton classes
• JToggleButton defines several constructors. The one used in our example is:
JToggleButton(String str)
• This creates a toggle button that contains the text passed in str. By default, the button is in
the off position
37
JTOGGLEBUTTON
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
• The JCheckBox class provides the functionality of a check box. It’s immediate
superclass is JToggleButton, which provides support for two-state buttons.
• JCheckBox defines several constructors. One is
JCheckBox(String str)
• It creates a check box that has the text specified by str as a label.
• When the user selects or deselects a check box, an ItemEvent is generated.
ItemEvent is passed to the itemStateChanged() method defined by
ItemListener.
JCHECKBOX EXAMPLE
• The following example displays four check boxes and a label. When the user clicks a
check box, an ItemEvent is generated.
• Inside the itemStateChanged() method, getItem() is called to obtain a reference to
the JCheckBox object that generated the event.
• Next, a call to isSelected() determines if the box was selected or cleared.
• The getText() method gets the text for that check box and uses it to set the text inside
the label.
JCHECKBOX
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
}
46
JRADIOBUTTON
• Radio buttons are a group of mutually exclusive buttons, in which only one button can
be selected at any one time.
• JRadioButton class extends JToggleButton.
• JRadioButton provides several constructors. The one is shown here:
• JRadioButton(String str)
• A button group is created by the ButtonGroup class. Elements are then added to the
button group using method:
• void add(AbstractButton ab)
• A JRadioButton generates action events, item events, and change events each time
the button selection changes.
48
JRADIOBUTTON EXAMPLE
• In following example three radio buttons are created and then added to a button
group.
• Pressing a radio button generates an action event, which is handled by
actionPerformed().
• Within that handler, the getActionCommand() method gets the text that is
associated with the radio button and uses it to set the text within a label.
JRADIOBUTTON
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
50
JRADIOBUTTON
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
52
JTABBEDPANE
54
JTABBEDPANE EXAMPLE
• Example illustrates a tabbed pane. The first tab is titled “Cities” and contains four buttons. Each
button displays the name of a city. The second tab is titled “Colors” and contains three check
boxes. Each check box displays the name of a color. The third tab is titled “Flavors” and contains
one combo box. This enables the user to select one of three flavors.
JTABBEDPANE
import javax.swing.*;
56
JTABBEDPANE
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}
58
JSCROLLPANE
60
JSCROLLPANE EXAMPLE
• Example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons are
added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the
scroll pane is added to the content pane. Because the panel is larger than the viewport,
vertical and horizontal scroll bars appear automatically. You can use the scroll bars to
scroll the buttons into view.
61
JSCROLLPANE
import java.awt.*;
import javax.swing.*;
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
62
JSCROLLPANE
private void makeGUI() {
` // Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane. Because the default border layout
// is used, the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
63
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 any
object that can be displayed.
• JList provides several constructors. Following constructor creates a JList that contains the
items in the array specified by items.
JList(Object[] items)
• A JList generates a ListSelectionEvent when the user makes or changes a selection or
deselects an item.
• It is handled by implementing ListSelectionListener. This listener specifies only one
method, called valueChanged()
• By default, a JList allows the user to select multiple ranges of items within the list, but you
can change this behavior by calling setSelectionMode()
64
JLIST
• Following applet demonstrates a simple JList, which holds a list of cities. Each time a city is selected
in the list, a ListSelectionEvent is generated, which is handled by the valueChanged() method
defined by ListSelectionListener. It responds by obtaining the index of the selected item and
displaying the name of the selected city in a label.
65
JLIST
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class JListDemo extends JApplet {
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle", "London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
66
JLIST
private void makeGUI() {
// Create a JList.
jlst = new JList(Cities);
}
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
}
}
68
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.
• The following JComboBox constructor initializes the combo box using items array
• JComboBox(Object[ ] items)
• 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.
• One way to obtain the item selected in the list is to call getSelectedItem() on the combobox.
69
JCOMBOBOX
• The following example demonstrates the combo box. The combo box contains entries for
“France,” “Germany,” “Italy,” and “Japan.” When a country is selected, an icon-based label is
updated to display the flag for that country.
70
JCOMBOBOX
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
• JTable is a component that displays rows and columns of data. You can drag the cursor on
column boundaries to resize columns. You can 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.
• JTable 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.
• JTable supplies several constructors. The one used here is
• JTable(Object data[][], Object colHeads[])
• Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-
dimensional array with the column headings.
73
JTABLE
• Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
74
JTABLE EXAMPLE
The following example illustrates how to create and use a simple table. A one-dimensional array of
strings called colHeads is created for the column headings. A two-dimensional array of strings called
data is created for the table cells. You can see that each element in the array is an array of three
strings. These arrays are passed to the JTable constructor. The table is added to a scroll pane, and
then the scroll pane is added to the content pane. The table displays the data in the data array. The
default table configuration also allows the contents of a cell to be edited. Changes affect the
underlying array, which is data in this case.
JTABLE
import java.awt.*;
import javax.swing.*;
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
76
JTABLE
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
77
JTABLE
// Create the table.
JTable table = new JTable(data, colHeads);
78
JTREE
• A tree is a component that presents a hierarchical view of data. The user has the ability to expand
or collapse individual subtrees in this display.
• Trees are implemented in Swing by the JTree class. One of the JTree constructor is shown below
• JTree(TreeNode tn) // tn is root node
• JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically placed
within a JScrollPane. This way, a large tree can be scrolled through a smaller viewport.
• Here are the steps to follow to use a tree:
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.
79
JTREE EXAMPLE
Example illustrates how to create a tree and handle selections. The program creates a
DefaultMutableTreeNode instance labeled “Options.” This is the top node of the tree hierarchy.
Additional tree nodes are then created, and the add() method is called to connect these nodes to
the tree. A reference to the top node in the tree is provided as the argument to the JTree
constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll
pane is then added to the content pane. Next, a label is created and added to the content pane.
The tree selection is displayed in this label. To receive selection events from the tree, a
TreeSelectionListener is registered for the tree. Inside the valueChanged() method, the path to the
current selection is obtained and displayed.
JTREE
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class JTreeDemo extends JApplet {
JTree tree;
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
81
JTREE
private void makeGUI() {
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
• Here is a program that creates a class called PaintPanel that extends JPanel.
The program then uses an object of that class to display lines whose
endpoints have been generated randomly. Sample output is shown here.
PAINT LINES TO A PANEL
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
// Construct a panel.
PaintPanel() {
// Put a border around the panel.
setBorder(BorderFactory.createLineBorder(Color.RED, 5));
rand = new Random();
}
85
PAINT LINES TO A PANEL
// Override the paintComponent() method.
protected void paintComponent(Graphics g) {
// Always call the superclass method first.
super.paintComponent(g);
int x, y, x2, y2;
// Get the height and width of the component.
int height = getHeight();
int width = getWidth();
// Get the insets.
ins = getInsets();
PaintDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Paint Demo");
// Give the frame an initial size.
jfrm.setSize(200, 150);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
88
THANK YOU!