Swings
G A N E S H PA I
A S S T. P R O F E S S O R G D I I I
D E PA RT M E N T O F C S E
N M A M I T, N I T T E
Textbook
Click to edit Master text styles
Second level
Third level
◦ Fourth level
◦ Fifth level
Swings GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 2
Overview of topics
Swings Introduction Swing Components
Introduction JLabel & ImageIcon
2 Key Features JTextField
MVC Connection The Swing Buttons
JButton, JToggleButton, JCheckBox,
Component & Containers
JRadioButton
Swing Packages
JTabbedPane
Simple Swing Application
JScrollPane
Event Handling in Swings
JList
Simple Swing Applet
JComboBox
JTable
Swings GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 3
Swings What are Swings?
Swings are a set of packages that provide tools to build GUI
Introduction applications
2 Key Features Swings are extension of AWT (Abstract Window Toolkit)
introduced by Sun Micro Systems
MVC Connection
Component & Containers AWT are earliest version of Java GUI
Swing Packages
Eg: Frame, Button, CheckBox, RadioButton
Simple Swing Application AWT contains heavy weight OS dependent components
Event Handling in Swings JFC (Java Foundation Classes) was developed in 1997 with JDK 1.2
Simple Swing Applet was later named as SWING
Eg: JFrame, JButton, JCheckBox, JRadioButton
Swing components are lightweight and native OS API independent
Swing API controls are rendered mostly using pure JAVA code
instead of underlying operating system calls
Hence faster with less memory.
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 4
GUI Components
Label Button Checkbox
ComboBox Scrollbar
Text Area
TextField List
Button
Radio Button Radio Button Group
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 5
Swing and AWT (contd…)
Swing built “on top of” AWT is bigger, faster, more flexible and better looking
Basic controls are practically the same in both
AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");
Swing gives far more options for everything (buttons with pictures on them, etc.)
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 6
Swing and threads
A thread is a lightweight process
Most Swing components are not thread-safe.
Solution is to make sure all code that creates and modifies Swing components executes in the
same 'event-dispatching' thread
Start a Swing application using the following code..
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 7
Swing and Threads - starting up
public static void main(String[] args)
{
SwingUtilities.invokeLater (new Runnable()
{
public void run()
{ createAndShowGUI(); // <<
method to start
}
});
}
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 8
Swing Components are Light Weight
Swings Written entirely in Java
Do not map directly to platform specific peers
Introduction
Rendered using Graphics Primitives
2 Key Features More efficient & more flexible
MVC Connection Look & Feel of each component is determined by Java
Component & Containers Thus each component will work in a consistent manner across all platform.
Swing Packages
Swing Supports a Pluggable Look & Feel (PLAF)
Simple Swing Application Look & Feel of each component is under the control of Swing
Event Handling in Swings Separates look & feel from logic of the component
Simple Swing Applet This makes it possible to change how the component is rendered independent
of other aspects
Alternately, it’s possible to “plug-in” a new look & feel for any given
component.
Possible to define entire set GUI style.
Thus can be made
consistent style across all platforms
platform specific style.
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 9
Look & Feel example
Metal CDE/Motif Windows
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 10
Swings 3 aspects of Visual Component
Introduction
MODEL: The state information associated with the
2 Key Features
component
MVC Connection
Component & Containers VIEW: The way that the component looks when rendered on
Swing Packages the screen
Simple Swing Application
CONTROLLER: The way that the component reacts to the user
Event Handling in Swings
Simple Swing Applet
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 11
Model-Delegate Architecture
Swing approach of MVC Combines View & Controller into a logical entity called UI delegate or
Model-Delegate or Separable Model Architecture
Swing components contain 2 objects:
First represents the model defined by Interfaces
ex. for Button -> ButtonModel
Second represents the UI Delegate defined by Classes that inherit ComponentUI
ex. for Button -> ButtonUI
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 12
Swings A GUI is built by putting components into containers
Components and Containers are the 2 key items of GU
Introduction
All containers are also components.
2 Key Features
MVC Connection
Component is an independent visual control
Ex: button, checkbox
Component & Containers
Container holds group of components
Swing Packages
For a component to be displayed, it should be within a
Simple Swing Application
container.
Event Handling in Swings
All Swing GUI will have at least 1 container enabling Swings
Simple Swing Applet to define containment hierarchy
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 13
Component & Containers
Components
2 types of components: Heavyweight & Lightweight
Heavyweight component
A heavyweight component is associated with its own native screen resource
Ex.: Components Button and Label from the java.awt package
Lightweight component
A lightweight component has no native screen resource of its own, hence
"lighter.“
It relies on the screen resource from an ancestor in the containment hierarchy,
possibly the underlying Frame object.
Ex.: Components JButton and Jlabel from javax.swing package
One can mix heavyweight and lightweight components within the same container
Swing components are derived from JComponent (with exception).
JComponent provides functionality that is common to all components.
It inherits AWT class Container and Component.
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 14
Component & Containers
Containers
2 types of Swing containers
Heavyweight containers (Top-level containers)
Lightweight containers
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 15
1. Top-level containers
JFrame, JApplet, JWindow, JDialog
These do not inherit JComponent
They inherit AWT class Component & Container
These must be at the top of containment hierarchy
These are not contained within any other container.
Every containment hierarchy must begin with a top-level hierarchy.
Usage of Container
JFrame for Applications
public class MyClass extends JFrame { }
JApplet for Applets
public class MyClass extends JApplet { }
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 16
2. Lightweight containers
They inherit JComponent
Eg: JPanel: a general purpose container
Often used to organize & manage group of related components.
Container can hold containers
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 17
Top-level container Panes
To appear on screen, every GUI component must be part of a
containment hierarchy, with a top-level container as its root
Each top-level container defines a set of panes
At the top is instance of JRootPane
It’s a lightweight container which manages other panes and optional
menu bar
Root Pane comprises of
Glass Pane
Layered Pane
Content Pane
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 18
Pane
Glass pane
Top level pane & Transparent instance of JPanel.
Sits above and covers all other panes.
Enables to manage mouse events that affect the entire container.
Layered Pane
Instance of JLayeredPane, providing components to be given depth in positioning
Determines which component overlays another (specify z-order for a component)
Holds content pane and optional menubar
Content Pane
Opaque instance of JPanel
Visual components are added here
Is the pane application interacts the most
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 19
Swings A very large sub-system makes use of many packages.
Main package is javax.swing.
Introduction
2 Key Features Contains classes that implement the basic Swing
components & must be imported into any swing program
MVC Connection
Component & Containers
Swing Packages SWING PACKAGE/SUB-PACKAGE LIST
Simple Swing Application javax.swing javax.swing.plaf.synth
Event Handling in Swings javax.swing.border javax.swing.table
Simple Swing Applet javax.swing.colorchooser javax.swing.text
javax.swing.event javax.swing.text.html
javax.swing.filechooser javax.swing.text.html.parser
javax.swing.plaf javax.swing.text.rtf
javax.swing.plaf.basic javax.swing.tree
javax.swing.plaf.metal javax.swing.undo
javax.swing.plaf.multi
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 20
To build a GUI…
Swings Make somewhere to display things (a Container)
Introduction
Usually you would use a JFrame or a JApplet
2 Key Features
Create some Components (buttons, text areas, panels, etc.)
MVC Connection
Declare Components as instance variables
Component & Containers
Define them in your applet’s init() method or in some
Swing Packages
application method
Simple Swing Application
Add your Components to your display area
Event Handling in Swings
Choose a layout manager
Simple Swing Applet
Add your Components to your JFrame or JApplet
Attach Listeners to your Components
Interacting with a Component causes an Event to occur
A Listener gets a message when an interesting event occurs,
and executes some code to deal with it
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 21
Simple Swing Application (using JFrame object)
import javax.swing.*;
Example:
class SwingDemo
{
SwingDemo()
{
JFrame jfrm = new JFrame("Simple Swing Application");
jfrm.setSize(300, 100);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("First Swing Program");
jfrm.add(jlab);
jfrm.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{ new SwingDemo(); }
});
}
}
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 22
Simple Swing Application (extending JFrame)
import javax.swing.*;
Example:
class SwingDemo extends JFrame
{
SwingDemo()
{
super("Simple Swing Application");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("First Swing Program");
add(jlab);
setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{ new SwingDemo(); }
});
}
}
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 23
Example Program
Swings Create 2 Buttons in JFrame
Introduction Create a Label, with default message “Press a button”, in JFrame
2 Key Features
MVC Connection
Component & Containers
Swing Packages
Add event listeners to each button
Simple Swing Application
If Button1 is clicked, display “Button1 was clicked” in Label
Event Handling in Swings
Simple Swing Applet
If Button2 is clicked, display “Button2 was clicked” in Label
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 24
import javax.swing.*; button2.addActionListener(new ActionListener(){
import java.awt.*; public void actionPerformed(ActionEvent e)
import java.awt.event.*; {
label.setText("Button2 was clicked");
public class EventDemo }
{ });
JLabel label;
jfrm.add(button1);
EventDemo() jfrm.add(button2);
{ jfrm.add(label);
JFrame jfrm = new JFrame("Swing Event Example");
jfrm.setVisible(true);
jfrm.setLayout(new FlowLayout()); }
jfrm.setSize(300, 100);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); public static void main(String args[])
{
JButton button1 = new JButton("Button1"); SwingUtilities.invokeLater(new Runnable() {
JButton button2 = new JButton("Button2"); public void run()
label = new JLabel("Press a button."); { new EventDemo();}
});
button1.addActionListener(new ActionListener(){ }
public void actionPerformed(ActionEvent e) }
{
label.setText("Button1 was clicked");
}
});
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 25
Example: Program
Swings
Introduction
java.lang.Object
2 Key Features |
MVC Connection java.awt.Component
|
Component & Containers java.awt.Container
Swing Packages |
java.awt.Panel
Simple Swing Application
|
Event Handling in Swings java.applet.Applet
Simple Swing Applet |
javax.swing.JApplet
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 26
import javax.swing.*; private void makeGUI()
import java.awt.*; {
import java.awt.event.*;
setLayout(new FlowLayout());
/*
<applet code="SwingAppletDemo" width="250" height="100"> button1 = new JButton("Button1");
</applet> button2 = new JButton("Button2");
*/ label = new JLabel("Press a button.");
public class SwingAppletDemo extends JApplet button1.addActionListener(new ActionListener(){
{ public void actionPerformed(ActionEvent e)
JButton button1, button2; {
JLabel label; label.setText("Button1 was clicked");
}
public void init() });
{
try button2.addActionListener(new ActionListener(){
{ public void actionPerformed(ActionEvent e)
SwingUtilities.invokeLater(new Runnable() { {
public void run() label.setText("Button2 was clicked");
{ makeGUI(); } }
}); });
}
catch(Exception e) add(button1);
{ System.out.println("Could not create: " + e); } add(button2);
add(label);
} }
}
Swings Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 27
End of Swing Introduction
Swing Introduction GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 28
Swing Components
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 29
Overview
JLabel & ImageIcon
JTextField
The Swing Buttons
JButton, JToggleButton, JCheckBox, JRadioButton
JTabbedPane
JScrollPane
JList
JComboBox
JTable
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 30
GUI Components
Label Button Checkbox
ComboBox Scrollbar
Text Area
TextField List
Button
Radio Button Radio Button Group
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 31
Component that displays text and/or an icon
Swing Components Constructors:
JLabel & ImageIcon JLabel(Icon icon)
JTextField JLabel(String str)
The Swing Buttons JLabel(String str, Icon icon, int align)
str and icon: text & icon used for the label
JTabbedPane
align: Horizontal alignment of text and/or icon.
JScrollPane Values: LEFT, RIGHT, CENTER, LEADING, TRAILING
JList
Object of Icon Interface is expected by JLabel
JComboBox
Can use ImageIcon instance which implements Icon
JTable
ImageIcon(String filename)
Methods of JLabel:
Icon getIcon( )
String getText( )
void setIcon(Icon icon)
void setText(String str)
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 32
JLabel Example Program
import javax.swing.*; private void makeGUI()
import java.awt.*; {
// Create an icon
public class JLabelDemo extends JApplet ImageIcon img = new ImageIcon("img/baby.jpg");
{
public void init() // Create a label
{ JLabel jlab = new JLabel(“Motivating", img, JLabel.CENTER);
try
{ // Add label to the content pane
SwingUtilities.invokeAndWait(new Runnable() { add(jlab);
public void run() }
{ makeGUI(); } }
});
}
catch(Exception e)
{ System.out.println("Could not create: " + e); }
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 33
Allows you to edit one line of text.
Swing Components Derived from JTextComponent.
JLabel & ImageIcon
Constructors:
JTextField
JTextField( )
The Swing Buttons
JTextField(int cols)
JTabbedPane
JTextField(String str)
JScrollPane JTextField(String str, int cols)
JList str: string to be presented
JComboBox cols: number of columns in the text field
JTable
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 34
JTextField Example
import javax.swing.*; private void makeGUI()
import java.awt.event.*; {
import java.awt.*; //Change to FlowLayout
setLayout(new FlowLayout());
public class JTextFieldDemo extends JApplet
{ // Add text field to content pane
JTextField jtf; jtf = new JTextField(15);
add(jtf);
public void init()
{ jtf.addActionListener(new ActionListener() {
try public void actionPerformed(ActionEvent ae)
{ {
SwingUtilities.invokeAndWait(new Runnable() { showStatus(jtf.getText());
public void run() }
{ makeGUI(); } });
}); }
} }
catch(Exception e)
{ System.out.println("Could not create: " + e); }
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 35
Swing defines 4 types of Buttons
Swing Components 1. JButton
JLabel & ImageIcon
2. JToggleButton
JTextField
3. JCheckBox
The Swing Buttons
4. JRadioButton
JTabbedPane All are subclasses of AbstractButton
JScrollPane AbstractButton Methods:
JList void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
JComboBox
void setSelectedIcon(Icon si)
JTable
void setRolloverIcon(Icon ri)
String getText( )
void setText(String s)
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 36
Swing Buttons
A Button generate an Action Event when they are pressed
Listeners register and unregister for these events via
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
The model used by all buttons is defined by ButtonModel interface.
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 37
1. JButton
Provides functionality of a push button
Allows an icon, a string, or both to be associated with the push button
Constructors:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
str & icon are string and icon used for the button
Action command string associated with that button can be obtained using
String getActionCommand() This identifies the button
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 38
// Add buttons to content pane
1. JButton Example JButton jb = new JButton(new ImageIcon("img/acro.png"));
jb.setActionCommand("Acrobat");
jb.addActionListener(this);
import javax.swing.*; add(jb);
import java.awt.event.*;
import java.awt.*; jb = new JButton(new ImageIcon("img/clock.png"));
jb.setActionCommand("Clock");
public class JButtonDemo extends JApplet implements ActionListener jb.addActionListener(this);
{ add(jb);
JLabel label;
jb = new JButton(new ImageIcon("img/penguin.png"));
public void init() { jb.setActionCommand("Penguin");
try { jb.addActionListener(this);
SwingUtilities.invokeAndWait(new Runnable() { add(jb);
public void run()
{ makeGUI(); } label = new JLabel("Chose any one"); // Add text field to content pane
}); add(label);
} catch(Exception e) }
{ System.out.println("Could not create: " + e); }
} public void actionPerformed(ActionEvent ae) {
label.setText("You selected: " + ae.getActionCommand());
private void makeGUI() }
{ }
setLayout(new FlowLayout()); //Change to FlowLayout
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 39
2. JToggleButton
Variation of push button
Looks like push button
Has 2 states: pushed & released.
When pressed, it stays pressed. (pushed state)
When again pressed, it’s released. (released state)
Superclass of JCheckBox & JRadioButton
Generates action event & item event each time clicked
To handle ItemEvent
Implement ItemListener interface
Event is passed to itemStateChanged()
Inside this, getItem() can be called to obtain the toggle button reference.
Object getItem()
boolean isSelected(): to get the state of the toggle button. Called by toggle button object.
true: selected
false:released
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 40
2. JToggleButton (contd …)
Constructors:
public JToggleButton ()
public JToggleButton(Icon icon)
public JToggleButton(Icon icon, boolean selected)
public JToggleButton (String text)
public JToggleButton (String text, boolean selected)
public JToggleButton(Action a)
public JToggleButton(String text, Icon icon)
public JToggleButton (String text, Icon icon, boolean selected)
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 41
2. JToggleButton Example
public class JToggleButtonDemo extends JApplet private void makeGUI()
{ {
JLabel label;
JToggleButton tbutton; setLayout(new FlowLayout()); //Change to FlowLayout
public void init() label = new JLabel("Button is Off"); //Create Label
{
try { tbutton = new JToggleButton("On/Off"); //Create a Toggle Button
SwingUtilities.invokeAndWait(new Runnable() {
public void run() tbutton.addItemListener(new ItemListener() {
{ makeGUI(); } public void itemStateChanged(ItemEvent ie)
}); {
} if(tbutton.isSelected())
catch(Exception e) label.setText("Button is On");
{ System.out.println("Could not create: " + e); } else
} label.setText("Button is Off");
}
});
add(tbutton);
add(label);
}
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 42
3. JCheckBox
Which provides the functionality of a check box
Constructors:
JCheckBox(Icon icon)
JCheckBox(Icon icon, boolean state)
JCheckBox(String str)
JCheckBox(String str, boolean state)
JCheckBox(String str, Icon icon)
JCheckBox(String str, Icon icon, boolean state)
icon: icon for the button
str: text
state: true, the check box is initially selected
state of the check box can be changed by
void setSelected(boolean state)
Generates ItemEvent each time clicked
Get the reference through getItem() on the ItemEvent passed to isStateChanged() defined by ItemListener
Get the state using isSelected() on the checkbox
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 43
3. JCheckBox Example
public class JCheckBoxDemo extends JApplet implements ItemListener private void makeGUI()
{ {
JLabel label; setLayout(new FlowLayout()); //Change to FlowLayout
public void init() JCheckBox cb = new JCheckBox("C");
{ cb.addItemListener(this);
try { add(cb); // Add check boxes to the content pane
SwingUtilities.invokeAndWait(new Runnable() {
public void run() cb = new JCheckBox("C++");
{ makeGUI(); } cb.addItemListener(this);
}); add(cb);
}
catch(Exception e) cb = new JCheckBox("Java");
{ System.out.println("Could not create: " + e); } cb.addItemListener(this);
} add(cb);
public void itemStateChanged(ItemEvent ie) cb = new JCheckBox(“Python");
{ cb.addItemListener(this);
JCheckBox cb = (JCheckBox) ie.getItem(); add(cb);
if(cb.isSelected())
label.setText(cb.getText() + " is selected"); label = new JLabel("Select Language"); //Create Label
else add(label);
label.setText(cb.getText() + " is cleared"); }
} }
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 44
4. JRadioButton
Which provides the functionality of a Radio button
Constructors:
JRadioButton()
JRadioButton(Action a)
JRadioButton(Icon icon)
JRadioButton(Icon icon, boolean state)
JRadioButton(String str)
JRadioButton(String str, boolean state)
JRadioButton(String str, Icon icon)
JRadioButton(String str, Icon icon, boolean state)
icon: icon for the button
str: text
state: true, the check box is initially selected
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 45
4. JRadioButton (contd …)
To provide mutually exclusive behavior RadioButton should be grouped
Created by ButtonGroup class
Default constructor is called to create.
Elements are added to the group using
void add(AbstractButton ab)
Generates ActionEvent, ItemEvent, ChangeEvent
One can implement ActionListener
To get the checked object
getActionCommand()
getSource()
Check each by isSelected()
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 46
4. JRadioButton Example
public class JRadioButtonDemo extends JApplet implements ActionListener private void makeGUI()
{ {
JLabel label; setLayout(new FlowLayout()); //Change to FlowLayout
public void init() ButtonGroup bg = new ButtonGroup();
{
try { JRadioButton rb = new JRadioButton("C++");
SwingUtilities.invokeAndWait(new Runnable() { rb.addActionListener(this);
public void run() add(rb);
{ makeGUI(); } bg.add(rb); // Add check boxes to the content pane
});
} rb = new JRadioButton("Java");
catch(Exception e) rb.addActionListener(this);
{ System.out.println("Could not create: " + e); } add(rb);
} bg.add(rb);
public void actionPerformed(ActionEvent ae) rb = new JRadioButton("Perl");
{ rb.addActionListener(this);
label.setText("You selected: " + ae.getActionCommand()); add(rb);
} bg.add(rb);
label = new JLabel("Select Language"); //Create Label
add(label);
}
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 47
Is a component that appears as a group of folders in a file cabinet
Swing Components Manages a set of components by linking them with tabs
JLabel & ImageIcon
Constructors:
public JTabbedPane()
JTextField
public JTabbedPane(int tabPlacement)
The Swing Buttons public JTabbedPane(int tabPlacement, int tabLayoutPolicy)
JTabbedPane
Tabs can be added using
JScrollPane
void addTabs(String name, Component comp)
JList name: name of the tab
JComboBox comp: component
JTable
General procedure to add
Create an instance of JTabbedPane
Add each tab by calling addTab( )
Add the tabbed pane to the content pane
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 48
class CitiesPanel extends JPanel {
public CitiesPanel()
JTabbedPane Example {
JButton b = new JButton("Mangalore"); add(b);
public class JTabbedPaneDemo extends JApplet b = new JButton("Bangalore"); add(b);
{ b = new JButton("Pune"); add(b);
public void init() b = new JButton("Calcutta"); add(b);
{ }
try { }
SwingUtilities.invokeAndWait(new Runnable() {
public void run() class ColorsPanel extends JPanel {
{ makeGUI(); } public ColorsPanel()
}); {
} JCheckBox cb = new JCheckBox("Red"); add(cb);
catch(Exception e) cb = new JCheckBox("Green"); add(cb);
{ System.out.println("Could not create: " + e); } cb = new JCheckBox("Blue"); add(cb);
} }
}
private void makeGUI()
{ class FlavorsPanel extends JPanel {
JTabbedPane jtp = new JTabbedPane(); public FlavorsPanel()
jtp.addTab("Cities", new CitiesPanel()); {
jtp.addTab("Colors", new ColorsPanel()); JComboBox jcb = new JComboBox();
jtp.addTab("Flavors", new FlavorsPanel()); jcb.addItem("Vanilla");
add(jtp); jcb.addItem("Chocolate");
} jcb.addItem("Strawberry");
add(jcb);
}
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 49
Lightweight container that handles scrolling of another
Swing Components component
JLabel & ImageIcon
Component being scrolled can be single component or group of
components
JTextField
Viewable area of the scroll pane is called viewport.
The Swing Buttons
JTabbedPane Steps that you should follow to use a scroll pane in an applet:
Create a JComponent object.
JScrollPane
Create a JScrollPane object passing to it the object to scroll.
JList
Add the scroll pane to the content pane.
JComboBox
JTable
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 50
JScrollPane (contd…)
Constructors:
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
comp: component to be added to the scroll pane.
vsb and hsb: int constants that define when vertical and horizontal scroll bars for this scroll pane
are shown. These constants are defined by the ScrollPaneConstants interface
◦ HORIZONTAL_SCROLLBAR_ALWAYS
◦ HORIZONTAL_SCROLLBAR_AS_NEEDED
◦ VERTICAL_SCROLLBAR_ALWAYS
◦ VERTICAL_SCROLLBAR_AS_NEEDED
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 51
JScrollPane Example
public class JScrollPaneDemo extends JApplet private void makeGUI()
{ {
public void init() JPanel jp = new JPanel();
{ jp.setLayout(new GridLayout(20, 20));
try {
SwingUtilities.invokeAndWait(new Runnable() { for(int i = 0; i < 10; i++)
public void run() for(int j = 0; j < 10; j++)
{ makeGUI(); } jp.add(new JLabel("New Message for scroll demo. "));
});
} //Create scroll pane
catch(Exception e) JScrollPane jsp = new JScrollPane(jp);
{ System.out.println("Could not create: " + e); }
} // Add scroll pane to the content pane
add(jsp, BorderLayout.CENTER);
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 52
Supports Selection of one or more items
Swing Components Can create list of any object other than strings
JLabel & ImageIcon Constructors:
JTextField public JList()
public JList(final Object[] listData)
The Swing Buttons
public JList(ListModel dataModel)
JTabbedPane
Long list are automatically scrollable
JScrollPane
JList
Generates ListSelectionEvent when user makes or changes a selection or
deselects an item.
JComboBox
Handled by implementing ListSelectionListener interface.
JTable
Specifies one method
void valueChanged(ListSelectionEvent le)
Packaged into javax.swing.event
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 53
JList (contd…)
Method:
void setSelectionMode(int mode)
Mode
◦ SINGLE_SELECTION
◦ SINGLE_INTERVAL_SELECTION
◦ MULTIPLE_INTERVAL_SELECTION (default)
int getSelectedIndex()
Begins at 0.
-1 if no item selected
Object getSelectedValue()
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 54
private void makeGUI()
JList Example
{
setLayout(new FlowLayout());
list = new JList(cities);
public class JScrollPaneDemo extends JApplet
{ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel label;
JList list;
spane = new JScrollPane(list);
JScrollPane spane; spane.setPreferredSize(new Dimension(120, 90));
String cities[] = {"Mangalore","Bangalore","Calcutta","Pune", label= new JLabel("Choose a city:");
"Chennai","Mysore","Mumbai","New Delhi"};
list.addListSelectionListener(new ListSelectionListener() {
public void init() public void valueChanged(ListSelectionEvent le) {
{
int index = list.getSelectedIndex();
try {
SwingUtilities.invokeAndWait(new Runnable() { if(index != -1)
public void run() label.setText("Current selection: " + cities[index]);
{ makeGUI(); }
else
}); label.setText("Choose a city");
} }
catch(Exception e) });
{ System.out.println("Could not create: " + e); }
} add(spane);
add(label);
}
}
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 55
Combination of Text Field and Drop-down list
Swing Components Constructor:
JLabel & ImageIcon JComboBox(Object[] items)
JTextField Uses ComboBoxModel.
The Swing Buttons Mutable combo box use MutableComboBoxModel.
JTabbedPane
Items can be added by
JScrollPane void addItem(Object ob)
JList
Generates Action Event on item select
JComboBox
Generates Item Event when state of selection changes.
JTable
To get the selected Item
Object getSelectedItem()
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 56
JComboBox Example
public class JComboBoxDemo extends JApplet private void makeGUI()
{ {
JLabel label; setLayout(new FlowLayout());
JComboBox cbox;
String cities[] = {"Mangalore","Bangalore","Calcutta","Pune", cbox = new JComboBox(cities);
"Chennai","Mysore","Mumbai","New Delhi"}; add(cbox);
public void init() cbox.addActionListener(new ActionListener() {
{ public void actionPerformed(ActionEvent ae)
try { {
SwingUtilities.invokeAndWait(new Runnable() { label.setText("You selected: " + cbox.getSelectedItem());
public void run() }
{ makeGUI(); } });
});
} label = new JLabel("Select a city");
catch(Exception e) add(label);
{ System.out.println("Could not create: " + e); } }
} }
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 57
Component that displays rows and columns of data
You can drag the cursor on column boundaries to resize columns
Swing Components
Constructor:
JLabel & ImageIcon
JTable(Object data[ ][ ], Object colHeads[ ])
JTextField
JTable does not provide any scrolling capability of its own.
The Swing Buttons
2 main JTable Events
JTabbedPane
List SelectionEvent
JScrollPane
When user selects something
JList TableModelEvent
JComboBox When table data changes
JTable JTable allows to select
One or more complete rows
One or more Columns
One or more individual cells
Swing Components GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 58
JTable Example
public class JTableDemo extends JApplet private void makeGUI()
{ {
public void init() final String[] colHeads = { "Name", "Phone", "Fax" }; // column headings
{
try { final Object[][] data = { // Initialize data
SwingUtilities.invokeAndWait(new Runnable() { { "Gail", "4567", "8675" }, a
public void run() { "Ken", "7566", "5555" },
{ makeGUI(); } { "Viviane", "5634", "5887" },
}); { "Melanie", "7345", "9222" },
} { "Anne", "1237", "3333" },
catch(Exception e) { "John", "5656", "3144" },
{ System.out.println("Could not create: " + e); } { "Matt", "5672", "2176" },
} { "Claire", "6741", "4244" },
{ "Erwin", "9023", "5159" },
{ "Ellen", "1134", "5332" },
{ "Jennifer", "5689", "1212" },
{ "Ed", "9030", "1313" },
{ "Helen", "6751", "1415" }
};
JTable table = new JTable(data, colHeads); // Create the table
JScrollPane spane = new JScrollPane(table); //Add the table to a scroll pane
add(spane); //Add scroll pane to content pane
}
Swings
}
GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 59
End of Swings
Swings GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 60