Module - 3
Module - 3
MODULE-3
Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two Key Swing Features, The MVC
Connection, Components and Containers, The Swing Packages, A Simple Swing Application, Event
Handling, Painting in Swing, Exploring Swing: JLabel and ImageIcon, JTextField, The Swing Buttons-
JButton, JToggleButton, Check Boxes, Radio Buttons
Introduction SWING
Swing contains a set of classes that provides more powerful and flexible GUI components than those of
AWT. Swing provides the look and feel of modern Java GUI. Swing library is an official Java GUI tool kit
released by Sun Microsystems. It is used to create graphical user interface with Java.
Swing is a set of program component s for Java programmers that provide the ability to create graphical user
interface (GUI ) components, such as buttons and scroll bars, that are independent of the windowing system
for specific operating system . Swing components are used with the Java Foundation Classes ( JFC ).
The Origins of Swing
The original Java GUI subsystem was the Abstract Window Toolkit (AWT). AWT translates it visual
components into platform-specific equivalents (peers).
Under AWT, the look and feel of a component was defined by the platform.
AWT components are referred to as heavyweight.
Swing was introduced in 1997 to fix the problems with AWT.
Swing offers following key features:
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Swing components are light weight and do not rely on peers.
7. Swing supports a pluggable look and feel.
8. Swing is built on AWT.
Model-View-Controller
One component architecture is MVC - Model-View-Controller.
The model corresponds to the state information associated with the component.
The view determines how the component is displayed on the screen. The controller determines how the
component responds to the user.
Swing uses a modified version of MVC called "Model-Delegate". In this model the view (look) and
controller (feel) are combined into a "delegate". Because of the Model-Delegate architecture, the look
and feel can be changed without affecting how the component is used in a program.
Components and Containers
• A component is an independent visual control: a button, a slider, a label, ... A container holds a group
of components. In order to display a component, it must be placed in a container.
• A container is also a component and can be contained in other containers. Swing applications create a
containment-hierarchy with a single top-level container.
Components
Swing components are derived from the JComponent class. The only exceptions are the four top-level
containers: JFrame, JApplet, JWindow, and JDialog.
JComponent inherits AWT classes Container and Component. All the Swing components are
represented by classes in the javax.swing package.
All the component classes start with J: JLabel, JButton, JScrollbar, ...
There are two types of containers:
1) Top-level which do not inherit JComponent, and
2) Lightweight containers that do inherit JComponent.
Lightweight components are often used to organize groups of components. Containers can contain other
containers.
Containers
All the component classes start with J: JLabel, JButton, JScrollbar etc.
Top-level Container Panes
Each top-level component defines a collection of "panes". The top-level pane is
JRootPane.
JRootPane manages the other panes and can add a menu bar.
There are three panes in JRootPane:
1) the glass pane,
2) the content pane,
3) the layered pane.
The content pane is the container used for visual components. The content pane is an instance of JPanel.
The Swing Packages:
Swing is a very large subsystem and makes use of many packages. These are the packages used by
Swing that are defined by Java SE 6.
The main package is javax.swing. 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.
Some of the Swing Packages are:
javax.swing javax.swing.plaf.synth
javax.swing.border javax.swing.table
javax.swing.colorchooserjavax.swing.text
javax.swing.eventjavax.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
A simple Swing Application;
There are two ways to create a frame:
By creating the object of Frame class (association) By extending Frame class(inheritance)
We can write the code of swing inside the main(), constructor or any other method.
By creating the object of Frame class
import javax.swing.*; public class FirstSwing{
public static void main(String[] args)
{
JFrame f=new JFrame(“ MyApp”);
//creating instance of JFrame and title of the frame is MyApp.
JButton b=new JButton("click");
//creating instance of JButton and name of the button is click.
b.setBounds(130,100,100, 40); //x axis, y axis, width, height
f.add(b); //adding button in JFrame
➢ Exploring Swings:
Jlabel:
JLabel is Swing’s easiest-to-use component. 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 defines several constructors.
Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
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. It is derived from JTextComponent, which
provides the basic functionality common to Swing text components. 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.
JPasswordField:
JPasswordField is a lightweight component that allows the editing of a single line of text where the
view indicates something was typed, but does not show the original characters.
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(10, 50, 70, 10);
JTextField userText = new JTextField();
userText.setBounds(80, 20, 100, 20);
JPasswordField passwordText = new JPasswordField();
passwordText.setBounds(80, 50, 100, 20);
f.add(namelabel);
f.add( passwordLabel);
f.add(userText);
f.add(passwordText);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
ImageIcon with JLabel
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 defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label.
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, LEADING,
or TRAILING.
These constants are defined in the Swing Constants interface, along with several others used by the
Swing classes. Notice that icons are specified by objects of type Icon, which is an interface defined by
Swing.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and
encapsulates an image. Thus, an object of type ImageIcon can be passed as an argument to the Icon
parameter of JLabel’s constructor. ImageIcon(String filename)
It obtains the image in the file named 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)
void setText(String str)
Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is possible to change
the text inside a label during program execution.
JToggleButton(String text, Icon icon, boolean selected): Creates a toggle button with the specified
text, image, and selection state.
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonExample extends JFrame implements ItemListener
{
public static void main(String[] args)
{
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample()
{
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton()
{
button = new JToggleButton("ON");
add(button);
}
private void setAction()
{
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve)
{
if (button.isSelected())
button.setText("OFF"); else
button.setText("ON");
}
}
After Clicking the Button…….
JRadioButton:
A JRadioButton is the swing equivalent of a RadioButton in AWT. It is used to represent multiple option
single selection elements in a form. This is performed by grouping the JRadio buttons using a
ButtonGroup component. The ButtonGroup class can be used to group multiple buttons so that at a time
only one button can be selected.
import javax.swing.*;
public class RadioButtonExample
{
JFrame f;
RadioButtonExample()
{
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30); r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
JCheckBox:
A JCheckBox is the Swing equivalent of the Checkbox component in AWT. This is sometimes called a
ticker box, and is used to represent multiple option selections in a form.
JCheckBox is a part of Java Swing package. JCheckBox can be selected or deselected.
It displays it state to the user.
JCheckBox is an implementation to checkbox.
JCheckBox inherits JToggleButton class.
import javax.swing.*;
class FirstSwing{
public static void main(String args[]){
JFrame jf=new JFrame("CheckBox");
JCheckBox jb=new JCheckBox("JAVA");
jb.setBounds(30, 100, 100, 50);
JCheckBox jb1=new JCheckBox("Python");
jb1.setBounds(30, 200, 100, 50);
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}
JScrollPane:
JScrollPane is a lightweight container that automatically handles the scrolling of another component.
• The component being scrolled can either be an individual component, such as a table, or a group of
components contained within another lightweight container, such as a JPanel.
• In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical
scroll bars are automatically provided, and the component can be scrolled through the pane. Because
JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars.
• The viewable area of a scroll pane is called the viewport. It is a window in which the component
being scrolled is displayed.
• Thus, the view port 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. For
example, if the component is taller than the viewport, a vertical scroll bar is added. If the component
will completely fit within the viewport, the scroll bars are removed.
• A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AL
WAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAY
S);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
JTabbedpane
• JTabbedPane encapsulates a 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.
• Tabbed panes are very common in the modern GUI. Given the complex nature of a tabbed pane, they
are surprisingly easy to create and use.
• JTabbedPane defines three constructors. We will use its default constructor, which creates an empty
control with the tabs positioned across the top of the pane. The other two constructors let you specify
the location of the tabs, which can be along any of the foursides.
• JTabbedPane uses the SingleSelectionModel model. Tabs are added by calling addTab() method.
Here is one of its forms:
void addTab(String name, Component comp)
• Here, name is the name for the tab, and comp is the component that should be added to the tab. Often,
the component added to a tab is a JPanel that contains a group of related components. This technique
allows a tab to hold a set of components.
f.setSize(500, 500);
f.setVisible(true);
}
}