Java and J2EE: Unit 4-
Swing
[email protected]
Nagaraja Hebbar N
Department of CSE, Srinivas Institute of Technology, Mangalore
UNIT – 4:Swing
Swings:
The origins of Swing;
Two key Swing features;
Components and Containers;
The Swing Packages;
A simple Swing Application;
Create a Swing Applet;
JLabel and ImageIcon;
JTextField;
The Swing Buttons;
JTabbedpane;
JScrollPane;
JList;
JComboBox;
JTable.
What is Swing?
Why Swing?
Early Java’s approach to GUI design was using AWT (Abstract Window Tool kit)
Experienced with lot of deficiencies.
These are tackled in Swing classes.
AWT defines a basic set of controls , windows and dialog boxes that support a
usable , but limited graphical interface
AWT translates various visual components into their corresponding, platform
specific equivalents
Look and feel of a components is defined by the platform (not by java)
AWT uses native code resources –so refereed to heavyweight
Before Swing: Abstract Window Toolkit
Abstract Window Toolkit (AWT)
Controls are components that allow a user to interact with your application in
various ways.
A layout manager automatically positions components within a container.
The appearance of a window is determined by a combination of the controls that it
contains and the layout manager used to position them.
A frame window can also include a standard-style menu bar.
Each entry in a menu bar activates a drop-down menu of options from which the
user can choose.
A menu bar is always positioned at the top of a window. Although different in
appearance, menu bars are handled in much the same way as are the other
controls.
Problems from AWT..
Variations between operating systems-components look differently in different
platforms
Violates the motto of Java “Write once run anywhere any time”
Look and feel of components was fixed and could not be changed
Heavyweight code put restriction ex: components were rectangle in shape,
opaque.
Swing introduced as part of Java in 1997 by Java Foundation Classes JFC.
Swing is now fully integrated in Java.
During Java 1.1, it was separate library.
Swing features
Swing is built on AWT
Swing does replace AWT
Still AWT is crucial part of Java
In GUI development , strict use AWT is now replaced by Swing components
Key features
AWT [Abstract Window Toolkit]is useful for developing simple user interface
Window Fundamental
Swing components are less dependent on target platform
Swing components are less of native GUI resource
Hence Swing are also known as lightweight components.
Key swing features
Swing components are lightweight
Written entirely in Java
Do not map directly to plat form specific peers
Light weight components are more flexible and efficient.
Look and feel is determined by swing not by Operating system
Swing support a pluggable Look and Feel(LAF)
Each swing component is rendered by Java code rather than by native peers
Look and feel is now separated from the logic of the components
So we could change Look and Feel of component without affecting any other aspects.
Pluggable look and feel is another advantage of swing
9 Component characteristics
contents, such as the state of a button (pushed in or not), or the text in a text field;
visual appearance (color, size, and so on)
behaviour (reaction to events).
Java and J2EE/NH/CS
The model-view-controller (MVC) design pattern
10
Implement three separate classes:
• The model, which stores the contents;
• The view, which displays the contents;
• The controller, which handles user input.
The pattern specifies precisely how these three objects interact.
Java and J2EE/NH/CS
11 Example for MVC
The controller handles the user input events-mouse clicks ..
It decides whether to translate these events into changes in the model or the
view.
For example, if the user presses a character key in a text box,
The controller calls the “insert character” command of the model.
The model then tells the view to update itself.
The view never knows why the text changed.
But if the user presses a key, then the controller may tell the view to scroll.
Scrolling the view has no effect on the underlying text, so the model never
knows that this event happened.
Java and J2EE/NH/CS
12 Components and containers
A swing GUI consist of: component and containers
Component: It is an independent visual control.
(Ex: Button)
A container holds a group of components.
(Ex: Dialog box, window etc.)
Swing components are derived from the JComponent class
Supports the pluggable look and feel
It inherits the AWT classes Container and Component
Java and J2EE/NH/CS
Components
Swing components are derived from Jcomponnets (except 4 top level
containers: JFrame, JApplet,JWindows,JDialog)
Provides functionalities common to all components.
Inherits from AWT classes
All swing components are defined within javax.swing package
Components hierarchy
Observations:
JApplet, JFrame,Jdialog are not inherited
from JComponents
All are inherited from AWT
So AWT is base for all swing components
and container class
(this hierarchy is incomplete )
15 Containers
Top level containers: JFrame, JApplet,JWindow and JDialog..
A top level container is not contained within any other container
Two top level containers used in application development are: Jframe and Japplet
The class either should extend JFrame or JApplet
Second type lightweight containers (Ex: JPanel) are used to manage or organize
group of related components.
Java and J2EE/NH/CS
Top-level Container pane
Layered pane allows components to be given with depth value
Content pane is opaque instance of JPanel
Panel
17
The simplest concrete subclass of Container
Window
Creates a window with no frame, no menu bar, and no title.
Components
An abstract super class for various AWT
Container
A subclass of Component that can hold other components
Frame
Creates a standard window that has a title bar, resize corners, and a menu bar.
Java and J2EE/NH/CS
Layout Manager
A layout manager is an object that performs the layout
computations for a container.
The AWT package has five common layout manager
classes and Swing has a few more
Flowlayout
Gridnlayout
Border layout
Card layout (not discussed)
Gridbag (not discussed)
How to set layout?
void setLayout(LayoutManager layoutobj)
layoutobj is reference to the desired layout manager
To disable layout manager( to consider default) use null value
Example: (detail in next slides)
contentPane.setLayout(new FlowLayout());
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT,100,20));
Default Layout Manager
20
Responsible for arranging components.
setLayout () method can be used to set layout (discussed earlier)
Default layouts:
JFrame: BorderLayout
JApplet: BorderLayout
JPanel: FlowLayout
NH/Java and J233/7CS-A/2012
21 Types of Layout
FlowLayout
Places components in rows from left to right.
Starts new row once previous row is filled.
BorderLayout
Places components in north,south,east,west, center.
GridLayout
Places in grid of cells in rows and columns.
CardLayout
The card layout manager. Card layouts emulate index cards. Only the one on top is
showing.
Grid bag layout
The grid bag layout manager. Grid bag layout displays components subject to the
constraints specified by GridBagConstraints.
NH/Java and J233/7CS-A/2012
Default layout ..
Adding and Removing Controls
To include a control in a window, you must add it to the window.
You must first create an instance of the desired control and then add it to a
window by calling add( ), which is defined by Container.
Component add(Component compObj);
24
Layout properties: FlowLayout
FlowLayout Constructor Parameters
Default ()
Align: Left, Right
hgap and vgap
contentPane.setLayout(new FlowLayout()); //Default layout
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT)); //set to left
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT,100,20)); //left and gaps
When a line is filled , advances to next line. (ex: close button in the next line)
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT,100,20));
jbtnOK=new JButton("Close");
JLabel lblUSN =new JLabel("Name:");
JTextField txtUSN=new JTextField(25);
contentPane.add(lblUSN);
contentPane.add(txtUSN);
contentPane.add(jbtnOK);
NH/Java and J233/7CS-A/2012
The flow layout manager :Example 2
----
The flow layout manager. Flow layout positions components left to right, top to bottom.
JPanel panel=new JPanel();
JButton ybutton =new JButton("Yellow");
JButton rbutton =new JButton("Red");
JButton gbutton =new JButton("Green");
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(ybutton);
panel.add(gbutton);
panel.add(rbutton);
add(panel);
----
26 Layout properties: BorderLayout
The border layout manager. Border layouts use five components: North, South, East, West, and
Center.
BorderLayout Constructor Parameters
Default ()
hgap and vgap
contentPane.setLayout(new BorderLayout());
contentPane.setLayout(new BorderLayout(int hgap, int vgap));
…
public SwingDemo5()
{
jbtnOK=new JButton("Close");
JLabel lblUSN =new JLabel("Name:");
JTextField txtUSN=new JTextField(25);
contentPane.add(lblUSN,BorderLayout.NORTH);//Up
contentPane.add(txtUSN,BorderLayout.WEST); //Left
contentPane.add(jbtnOK,BorderLayout.EAST);//right
}
----
NH/Java and J233/7CS-A/2012
Border Layout Example 2
The border layout manager. Border layouts use five components: North, South, East, West,
and Center.
JPanel Borderpanel=new JPanel();
JButton bTop =new JButton("Top");
JButton bBottom =new JButton("Bottom");
JButton bLeft =new JButton("Left");
JButton bRight =new JButton("Right");
JButton bCenter =new JButton(“Center");
Borderpanel.setLayout(new BorderLayout());
Borderpanel.add(bBottom,BorderLayout.SOUTH);
Borderpanel.add(bRight,BorderLayout.EAST);
Borderpanel.add(bLeft,BorderLayout.WEST);
Borderpanel.add(bTop,BorderLayout.NORTH);
Borderpanel.add(bCenter,BorderLayout.CENTER);
add(Borderpanel);
}
}
Layout properties: GridLayout
28
GridLayout: Constructor Parameters
Rows ,columns
Rows columns ,hgap and vgap
contentPane.setLayout(new GridLayout(int rows, int columns));
contentPane.setLayout(new GridLayout(int rows, int columns,int hgap, int vgap));
…
public SwingDemo5(){
contentPane = getContentPane();
contentPane.setLayout(new GridLayout(3,1));
//contentPane.setLayout(new GridLayout(1,3));
jbtnOK=new JButton("Close");
JLabel lbl =new JLabel("Name:");
JTextField txt=new JTextField(25);
contentPane.add(lbl);
contentPane.add(txt);
contentPane.add(jbtnOK);
NH/Java and J233/7CS-A/2012
}
GridLayout Example 2
The grid layout manager. Grid layout displays components i n a two-
dimensional grid.
JButton ybutton =new JButton("Yellow");
JButton rbutton =new JButton("Red");
JButton gbutton =new JButton("Green");
panel.setLayout(new GridLayout(1,3));
add(panel);
---
30
JPanel: Revisited
public SwingDemo() // contructor
{ Panels may be used as container to hold components
Default layout in Panel is : flow layout, left to right orientation
setTitle("User Interface...... ");
setSize(450,400);
contentPane = getContentPane();
jbtn=new JButton("Close");
lbl =new JLabel("Name:");
txt=new JTextField(25);
panel=new JPanel(new GridLayout(1,3)); //this panel's Grid 1X3
panel.add(lbl);
panel.add(txt);
panel.add(jbtn);
contentPane.add(panel);
}
NH/Java and J233/7CS-A/2012
Swing Application :simple version
import javax.swing.*; class SimpleFrameDemo extends Jframe //extended from JFrame class
public class SwingGUI1SimpleFrame { {
public static void main(String[] args) { ImageIcon imagebox;
public SimpleFrameDemo()
SwingUtilities.invokeLater(new Runnable()
{
{ public void run() {new SwingDemo1();}} ); setTitle("User Interface...... ");
} setSize(200,200);
} }
class SwingDemo1 }
{
public SwingDemo1()
{
SimpleFrameDemo frame=new SimpleFrameDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
About first Swing application
Use Javax.swing.* package to utilize all wing classes.
Create customized frame
Set default close operation
By default when top level windows is closed , the window is removed from screen.
But application still running, to terminate application when top level is closed use:
setDefaultCloseOperation. On exit of Close i.e JFrame.EXIT_ON_CLOSE
Other possible values are: DISPOSE_ON_CLOSE, HIDE_ON_CLOSE,DO_NOTHING_ON_CLOSE
Set size of the frame as per requirement (setsize(width,height);)
Event handling thread in swing:
Inside main() , object of this application is created on event handling thread rather
than main thread of the application.
Swing programs are event driven, events are called on a thread , that was not created
by application program.
To handle this event handling situation application object is not created by main
rather Runnable object that executes on the event handling thread
To enable GUI code to be created on the event handling thread , we must use one of
the two methods of swing utilities
invokeLater
invokeAndWait
Runnable object will have its run() method called by the event dispatching thread.
Swing Applet: simple version
import javax.swing.*; public void SwingDemoApplet()
public class SwingGUI1SimpleFrameApplet extends JApplet
{
{
Frame c = (Frame)this.getParent().getParent();
Container contentPane;
public void init()
//parent of the Applet is AppletViewerPanel and its parent is
AppletViewe
{
try
c.setTitle("User Interface:Simple Frame (Applet).....");
{ }
SwingUtilities.invokeLater(new Runnable(){ }
public void run(){SwingDemoApplet();}});
}
catch(Exception e){}
}
Swing Application: JLabel
35
Constructors and Methods
JLabel(String text);
Constructs Label with left aligned text.
JLabel(Icon icon);
Constructs a label with left aligned icon
JLabel(String text,int align);
Constructs a label with specified alignment
Align: LEFT, RIGHT, CENTER
JLabel(String text,int align);
Constructs a label with specified alignment and icon
Icon Left of Text
NH/Java and J233/7CS-A/2012
JLabel: Methods
The icon and text associated with the label can be read
and written by the following methods:
Icon getIcon( ) //returns icon that was set
String getText( )//returns text
void setIcon(Icon i)//sets image
void setText(String s) //sets text
Here, i and s are the icon and text, respectively.
ImageIcon
37
To obtain image icon
The object of type ImageIcon can be passed as an
argument to the icon parameter of Jlabel’s
constructor.
Constructor: ImageIcon(String filename)
Icon and text associated with the label can be
obtained by: Icon getIcon()
String getText()
Icon and text associated with a label can be set by:
void setIcon(Icon icon)
void setText(String str)
Java and J2EE/NH/CS
JLabel and ImageIcon
38
Constructors and Methods
void setText(String text); Sets the text of the Label
void setIcon(Icon icon); Sets the icon of the Label
Note: Complete program: SwingColorFontImageLabel.java
NH/Java and J233/7CS-A/2012
How to set image to label?
lbl=new JLabel("My Swing Example..");
lbl.setIcon(imagebox);
How to change default application icon?
imagebox=new ImageIcon(getClass().getResource("Image1.gif"));
setIconImage(imagebox.getImage());
JTextField
41 It is a text component of swing, used to edit one line of text
Constructors and Methods
JTextFields(int cols);
creates text field and sets size to cols
JTextFields(String str);
creates text field, and initializes text also
JTextFields(String str,int cols);
creates text field, sets size to cols and initialzes text aslo
NH/Java and J233/7CS-A/2012
42 JTextField
Str: string to be initialized, Cols: number of columns in the text
field
If no string is specified, the string is set to empty
ActionEvent is fired when the user presses ENTER
CaretEvent is fired when cursor changes its
position
Java and J2EE/NH/CS
JTextField
43 Constructors and Methods
void setText(String text);
Sets the text of the TextField
void setColumns (int cols);
Sets no. of columns
String getText();
Returns the text from the TextField
txt1=new JTextField("Source");
txt2=new JTextField();
txt2.setText(txt1.getText());
panel=new JPanel();
panel.add(lbl);
panel.add(txt1);
panel.add(txt2);
NH/Java and J233/7CS-A/2012
44
JTextArea
Constructors and Methods
JTextArea(int row,int cols);
creates text field and sets size to cols and rows
JTextFields(String str, int row,int cols);
creates text field, and initializes text and sets rows and column
Constructors and Methods
void setColumns(int cols); sets column
void setRows(int rows); sets rows
void append(String text); appends given text to end of text that it has
void setLineWrap(boolean wrap); toggles line wrap
NH/Java and J233/7CS-A/2012
JTextArea(contd..)
45
txt1=new JTextArea();
txt1.setColumns(8);
txt1.setRows(2);
txt1.setLineWrap(true);
txt2=new JTextArea();
txt2.setText(txt1.getText());
Complete Program:SwingTextFieldDemo.java
NH/Java and J233/7CS-A/2012
46 JPasswordField
To hide characters typed in with echo character.
Constructor:
JPasswordField(String text,int cols);
Methods
void setEchoChar(char echo);
Sets echo character
char[] getPassWord()
Returns the text contained in PasswordField
Overwrite the array after use
NH/Java and J233/7CS-A/2012
How to use password field
passTxt=new JPasswordField(14); //create password field
passTxt.setEchoChar('*'); //set password character
char[] pass=passTxt.getPassword(); //get password from password field
String StrPassword="";
for(int i=0;i<pass.length;i++)
{
StrPassword=StrPassword+pass[i]; /clear password char array for safety purpose
pass[i]='\0';
}
Complete Program:SwingPasswordDemo.java
48
Swing Buttons
JButton
JToggleButon
JCheckBox
JRadioButton
These are subclasses of AbstractButtonClass
Extends from Jcomponents
Common Methods
Void setDisabledIcon(Icon di)
Void setPressedIcon(Icon dp)
Void setSelectedIcon(Icon si)
Void setRolloverIcon(Icon ri)
String getText()
void setText(String str)
NH/Java and J233/7CS-A/2012
49 Buttons-JButton
Constructors:
JButton(Icon icon)
JButton(String str)
JButton(String str,Icon icon)
Methods:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon di)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
String getText()
void setText(String str)
String Java
getActionCommand():This
and J2EE/NH/CS
identifies buttons
50
JButton
Events
When the button is pressed, an ActionEvent is generated.
Using ActionEvent object passed to the actionPerformed () method
of the registered ActionListener. You can obtain the action
command string associated with the button.
String getActionCommand()
This identifies the button among other buttons within the same application.
Complete example:SwingButtonDemo.java
NH/Java and J233/7CS-A/2012
Toggle Button
51
Constructor:
JToggleButton(String str)
Method
boolean isSelected();
Events
Implements: ItemListener
Method to implemented:
itemStateChanged(ItemEvent ae){..}
Complete example:SwingToggleDemo.java
NH/Java and J233/7CS-A/2012
Check Boxes
52
JCheckBox class provides the functionality of a check box.
Constructor: JCheckBox(String str)
When the user selects /deselects a check box, an ItemEvent is generated
Object reference can be obtained by getItem()
State of the check is determined by isSelected()
Example:
c1 = new JCheckBox("PU");
c1.addActionListener(acl1);
if (c1.isSelected()) br1="PU ";
Complete example: SwingCheckBox.java
Java and J2EE/NH/CS
Radio Buttons
53
Group of mutually exclusive buttons
Only one button (in a group) can be selected at any time.
Constructor: JRadioButton(String str)
JRadioButton generates: action, item, change events each time the button selection changes.
ActionListener interface is implemented with method actionPerformed
Example:
rbtn1 = new JRadioButton("A");
group.add(rbtn1);
rbtn1.setActionCommand("A");
rbtn1.addActionListener(acl1);
Complete example:SwingRadioButton.java
Java and J2EE/NH/CS
54
JScrollPane
It is a lightweight container that automatically handles the scrolling of another
component.
The component being can either be an individual component , such as a table, or
a group of components contained within another lightweight container such as
JPanel.
If 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.
Constructor: JScrollPane(Component comp)
Genear Steps to followed:
1. Create the component to be scrolled (Textarea)
2. Create an instance of JScrollPane, passing to it the object to scroll
3. Add the scroll pane to the content pane.
Java and J2EE/NH/CS
ScrollPane (Steps explained)
JTextArea textArea = new JTextArea(8, 40);
textArea.setText("The quick brown fox jumps over the lazy dog.");
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane, BorderLayout.CENTER);
56 JTabbedPane
Encapsulates tabbed pane
It manages a set of components by linking them with tabs
Selecting a tab causes the component associated with that tab to come to the forefront
Constructor: JTabbedPane();
Tabs are added by calling addTab()
Void addTab(String name,Component comp)
name: is name of the tab;
comp: is the component that should be added to the tab
General procedure to use a tabbed pane:
Create an instance of JTabbedPane
call addTab to add each tab
Add the tabbed pane to the content pane.
Java and J2EE/NH/CS
JTabbedPaneScrollPane (Steps explained)
JTabbedPane Jtab = new JTabbedPane();
Jtab.addTab(“Tab1”, new JLabel(“Hello”);
Jtab.addTab(“Tab2”, new JLabel(“Hai”);
contentPane.add(Jtab);
58 JList
Supports the selection of one or more items from a list.
Constructor
In Java 7: JList<E> where E is type of item in the class ; a generic class
(Previous version )Constructor: JList (E[] items)
JList contains the items in the array specified by items.
Methods
setSelectionMode(int mode) // to set or deselect multiselect list box
Values: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION,MULTIPLE_INTERVAL_SELECTION
getselectedIndex(): returns index of item selected (index starts from 0) -1 means no item selected
Events:
ListSelectionEvent: generated when user makes or changes a selection, also when deselects handled by
ListSelectionListener:
The listener specifies only one method: Valuechanged(ListSelectionEvent e) method
Java and J2EE/NH/CS
JList -exampe
String[] El2 ={".Net","DIP","GT","AI","VLSI","FL"};
list1=new JList<String> (El2);
ListSelectionListener acl1=new ListSelection();
list1.addListSelectionListener(acl1);
JScrollPane jsp1=new JScrollPane(list1);
jsp1.setPreferredSize(new Dimension(120,70));
p.add(jsp1);
-- -
private class ListSelection implements ListSelectionListener{
public void valueChanged(ListSelectionEvent ae){
txtField.setText(list1.getSelectedValue());
}}
Complete example:SwingList.java
60 JCombo
Combo provides combination of a textfield and a drop down list, It normally displays one
entry, but it will also display a drop down list that allows a user to select a different entry.
Constructor
In Java 7: JCombo<E> where E is type of item in the class ; a generic class
(Previous version )Constructor: JCombo (E[] items)
JList contains the items in the array specified by items.
Methods
addItem(E obj) used only with mutable combo box to add items dynamically
getSelectedItem() returns selected item (Object type)
Events:
ActionEvent which implements ActionListener and uses method actionPerformed
Java and J2EE/NH/CS
JCombo:Example
JComboBox<String> cmbo1;
ActionListener acl1;
acl1=new CommandActionCombo();
String[] El1={"ADBMS","DSP","Java","DM","MC","NN"};
cmbo1=new JComboBox<String> (El1);
cmbo1.addActionListener(acl1);
p.add(cmbo1);
private class CommandActionCombo implements ActionListener {
public void actionPerformed(ActionEvent ae){
txtField.setText((String)cmbo1.getSelectedItem());
}
}
Complete example:SwingCombo.java
JTable
62 Displays rows and columns of data
User can drag corner to resize the columns
Constructor: JTable(Object data[][],Object colHeads[]);
Steps:
Create an instance of JTable
Create a JScrollPane object
Add the table to the scroll pane
Add the scroll pane to the content pane
Java and J2EE/NH/CS
JTable example
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Name");
model.addColumn("USN");
JScrollPane jsp1=new JScrollPane(table);
jsp1.setPreferredSize(new Dimension(300,100));
JPanel p2=new JPanel();
p2.add(jsp1);
Complete example: SwingTable.java
Working with Color ( Additional information)
Color class: constructor: Color(int red,int green,int blue);
Jlable lbl=new Jlabel(“SSSSSS”);
lbl.setBackground(new Color(100,220,230));
lbl.setForeground(new Color(100,100,100));
Complete example:SwingColorFontImageLabel.java
Working with Font ( Additional information)
Class: Font class
Constructor: Font(String Fontname, int fontstyle,int fontsize)
lbl.setFont(new Font("serif",Font.BOLD+Font.ITALIC,12));
Complete example:SwingColorFontImageLabel.java
Dimension object
Class Dimension(int width,int height )
jsp1.setPreferredSize(new Dimension(300,100));
Reference
Java Complete Reference 8th ed author Herbert schildt
Internet resources