Java Swing Overview and Features
Java Swing Overview and Features
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.
Java Foundation Classes (JFC):
JFC is an extension of original AWT. It contains classes that are completely portable, since the entire JFC is
developed in pure Java. Some of the features of JFC are:
2. JFC components have same look and feel on all platforms. Once a component is created, it looks same on
any OS.
3. JFC offers “pluggable look and feel” feature, which allows the programmer to change look and feel as
suited for platform. For, ex if the programmer wants to display window-style button on Windows OS, and
Unix style buttons on Unix, it is possible.
4. JFC does not replace AWT, but JFC is an extension to AWT. All the classes of JFC are derived from
AWT and hence all the methods in AWT are also applicable in JFC. So, JFC represents class library
developed in pure Java which is an extension to AWT and swing is one package in JFC, which helps to
develop GUIs and the name of the package is import [Link].*; Here x represents that it is an ‘extended
package’ whose classes are derived from AWT package.
1
[Link] unit III
1. Platform Independence: Platform independence is one of Java Swing’s most remarkable features. It can run
on any platform that supports Java. Thus, Swing-based applications can run on Windows, Mac, Linux, or any
other Java-compatible operating system.
2. Lightweight Components: Java Swing provides a set of lightweight components that are easy to use and
customizable. These components are designed to consume less memory and use less processing power,
making Swing-based applications run efficiently.
3. Pluggable Look and Feel: Java Swing provides a pluggable look and feels that allows developers to
customize the appearance of the GUI according to the user’s preferences. Developers can choose from
several pre-built looks and feel themes or create their own custom themes.
4. Layout Managers: Java Swing provides a set of layout managers that can be used to organize the graphical
components in a GUI. These layout managers enable developers to create flexible and responsive GUIs that
adapt to different screen sizes and resolutions.
5. Robust Event Handling Mechanism: Java Swing provides a robust event handling mechanism that allows
developers to handle events generated by the graphical components. Developers can register event listeners
to detect and respond to user interactions with the GUI.
2
[Link] unit III
Components and Containers:
components and containers. However, this distinction is mostly conceptual because all containers are
also components. The difference between the two is found in their intended purpose: As the term is
commonly used, a component is an independent visual control, such as a push button or slider. A container
holds a group of components. Thus, a container is a special type of component that is designed to hold other
components. Furthermore, in order for a component to be displayed, it must be held within a container. Thus,
all Swing GUIs will have at least one container. Because containers are components, a container can also
hold other containers. This enables Swing to define what is called a containment hierarchy, at the top of
which must be a top-level container.
Some of the important and common components of the Java Swing class are:
JComponent:
3
[Link] unit III
JLabel:
– JLabel(string str)
– JLabel(Icon i)
• Icon – is an interface
– The easiest way to obtain icon is to use ImageIcon class. ImageIcon class implements Icon interface.
Important Methods:
Icon getIcon()
String getText()
JText Fields
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It provides
functionality that is common to Swing text components. One of its subclasses is JTextField, which allows you to edit
one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the number of columns in the text field.
The following example illustrates how to create a text field. The applet begins by getting its content pane, and
then a flow layout is assigned as its layout manager. Next, a JTextField object is created and is added to the content
pane.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
JTextField jtf;
MyFrame() {
setLayout(new FlowLayout());
jl2=new JLabel();
jtf=new JTextField("PVPSIT",15);
add(jl);
5
[Link] unit III
add(jtf);
add(jl2);
[Link](this);
[Link]([Link]());
class FrameDemo
[Link]("Welcome to Swings");
[Link](500,500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}}
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. Some of its constructors are shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
6
[Link] unit III
Here, s and i are the string and icon used for the button.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
JButton jb,jb1,jb2;
JLabel jl;
MyFrame()
setLayout(new FlowLayout());
jl=new JLabel();
jb=new JButton("VRSEC");
jb1=new JButton("PVPSIT",ii);
add(jb);
add(jb1);
add(jb2);
add(jl);
[Link](this);
[Link](this);
[Link](this);
7
[Link] unit III
}
}}
[Link]("Welcome to Swings");
[Link](500,500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}}
JCheckBox:
The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of
AbstractButton. Its immediate super class is JToggleButton, which provides support for two-state buttons (true or
false). Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(String s)
JCheckBox(String s, Icon i)
Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially selected.
Otherwise, it is not.
The state of the check box can be changed via the following method:
8
[Link] unit III
void setSelected(boolean state)
Here, state is true if the check box should be checked. When a check box is selected or deselected, an item event is
generated. This is handled by itemStateChanged( ). Inside itemStateChanged( ), the getItem( ) method gets
the JCheckBox object that generated the event. The getText( ) method gets the text for that check box and uses it to
set the text inside the text field.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
JCheckBox jcb,jcb1,jcb2;
JLabel jl;
MyFrame()
setLayout(new FlowLayout());
jl=new JLabel();
jcb=new JCheckBox("VRSEC");
jcb1=new JCheckBox("PVPSIT");
jcb2=new JCheckBox("BEC" );
add(jcb);
add(jcb1);
add(jcb2);
add(jl);
[Link](this);
[Link](this);
9
[Link] unit III
[Link](this);
JCheckBox jc=(JCheckBox)[Link]();
}}
class FrameDemo
[Link]("Welcome to Swings");
[Link](500,500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}}
JRadioButton:
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton.
Its immediate superclass is JToggleButton, which provides support for two-state buttons. Some of its constructors are
shown here:
JRadioButton(Icon i)
JRadioButton(String s)
JRadioButton(String s, Icon i)
10
[Link] unit III
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected.
Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at any time.
For example, if a user presses a radio button that is in a group, any previously selected button in that group is
automatically deselected. The ButtonGroup class is instantiated to create a button group. Its default constructor is
invoked for this purpose. Elements are then added to the button group via the following method: void
add(AbstractButton ab)
Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method returns the text that is associated with a radio button and
Example:
import [Link].*;
import [Link].*;
import [Link].*;
class MyFrame extends JFrame implements ActionListener { JRadioButton jrb,jrb1,jrb2; JLabel jl; MyFrame()
{ setLayout(new FlowLayout());
jl=new JLabel();
jrb=new JRadioButton("VRSEC");
jrb1=new JRadioButton("PVPSIT");
jrb2=new JRadioButton("BEC" );
add(jl);
[Link](jrb);
[Link](jrb1);
[Link](jrb2);
11
[Link] unit III
[Link](this);
[Link](this);
[Link](this);
}}
class FrameDemo
[Link]("Welcome to Swings");
[Link](500,500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
JComboBox :
Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox
class, which extends JComponent.
A combo box normally displays one entry. However, it can also display a drop-down list that allows a user to select a
different entry. You can also type your selection into the text field.
JComboBox( )
JComboBox(Vector v)
12
[Link] unit III
Here, v is a vector that initializes the combo box. Items are added to the list of choices via the addItem( ) method,
whose signature is shown here:
By default, a JComboBox component is created in read-only mode, which means the user can only pick one item from
the fixed options in the drop-down list. If we want to allow the user to provide his own option, we can simply use the
setEditable() method to make the combo box editable.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
JComboBox jcb;
MyFrame()
setLayout(new FlowLayout());
String cities[]={"Amaravati","Guntur","Vijayawada","Vizag","Kurnool"};
jcb=new JComboBox(cities);
[Link]("Tirupati");
[Link](true);
add(jcb);
[Link](this);
13
[Link] unit III
[Link](null,[Link]());
}}
[Link](500,500);
[Link](true);
[Link]("Frame Example");
[Link](JFrame.EXIT_ON_CLOSE);
}}
JList:
• JList class is useful to create a list which displays a list of items and allows the user to select one or more items. –
Constructors
• JList()
• JList(Object arr[])
• JList(Vector v)
– Methods
• getSelectedIndices() – returns selected items into an array • getSelectedValues() – returns selected items names
into an array
14
[Link] unit III
– ListSelectionListener
• void valueChanged(ListSelectionEvent)
– Package is [Link].*;
Example:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
JLabel jl;
JList j;
MyFrame()
setLayout(new FlowLayout());
j=new JList(arr);
add(jl);
add(j);
[Link]("I am PVPSIT");
[Link](this);
{
15
[Link] unit III
[Link](null, [Link]());
}}
[Link]("Welcome to Swings");
[Link](500,500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}}
16
[Link] unit III
Glass pane: This is the first pane and is very close to the monitor’s screen. Any components to be displayed in
the foreground are attached to this glass pane. To reach this glass pane we use getGlassPane() method of JFrame class,
which return Component class object.
Root Pane: This pane is below the glass pane. Any components to be displayed in the background are
displayed in this frame. To go to the root pane, we can use getRootPane() method of JFrame class, which
returns component class object.
JRootPane object.
Layered pane:
This pane is below the root pane. When we want to take several components as a group, we attach them in the
layered pane. We can reach this pane by calling getLayeredPane() method of JFrame class which returns
JLayeredPane class object.
Conent pane: This is bottom most of all, Individual components are attached to this pane. To reach this pane,
we can call getContentPane() method of JFrame class which returns Container class object.
1. JFrame: JFrame is a top-level container that represents the main window of a GUI application. It provides a
title bar, and minimizes, maximizes, and closes buttons.
2. JPanel: JPanel is a container that can hold other components. It is commonly used to group related
components together.
3. JButton: JButton is a component that represents a clickable button. It is commonly used to trigger actions in
a GUI application.
4. JLabel: JLabel is a component that displays text or an image. It is commonly used to provide information or
to label other components.
5. JTextField: JTextField is a component that allows the user to input text. It is commonly used to get input
from the user, such as a name or an address.
6. JCheckBox: JCheckBox is a component that represents a checkbox. It is commonly used to get a binary
input from the user, such as whether or not to enable a feature.
7. JList: JList is a component that represents a list of elements. It is typically used to display a list of options
from which the user can select one or more items.
8. JTable: JTable is a component that represents a data table. It is typically used to present data in a tabular
fashion, such as a list of products or a list of orders.
9. JScrollPane: JScrollPane is a component that provides scrolling functionality to other components. It is
commonly used to add scrolling to a panel or a table.
17
[Link] unit III
JFrame: Frame represents a window with a title bar and borders. Frame becomes the basis for creating the
GUIs for an application because all the components go into the frame.
To create a frame, we have to create an object to JFrame class in swing as JFrame jf=new JFrame(); // create a
frame without title
JFrame jf=new JFrame(“title”); // create a frame with title
To close the frame, use setDefaultCloseOperation() method of JFrame class.
setDefaultCloseOperation(constant)
Example:
To set the background import [Link].*;
import [Link].*;
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("HVPM");
[Link](200,200);
[Link](true);
Container c=[Link]();
[Link]([Link]);
}
18
[Link] unit III
JApplet:
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be
subclasses of JApplet. JApplet is rich with functionality that is not found in Applet. For example, JApplet
supports various “panes,” such as the content pane, the glass pane, and the root pane.
One difference between Applet and JApplet is, When adding a component to an instance of
JApplet, do not invoke the add( ) method of the applet. Instead, call add( ) for the content pane of the JApplet
object.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
Example
import [Link].*;
import [Link].*;
public class ContainerTest extends JFrame
{
// top-level container
JPanel panel; // low-level container
JTextField field;
JButton btn;
public ContainerTest() {
setTitle("Container Test");
panel = new JPanel();
field = new JTextField(20);
[Link](field);
btn = new JButton("Submit");
[Link](btn);
add(panel, [Link]);
setSize(350, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new ContainerTest();
19
[Link] unit III
}
}
� The Accessibility package: This package defines a contract between Java UI objects (such as screen
readers, Braille terminals, and so on) and screen access products used by people with disabilities.
Swing components fully support the accessibility interfaces defined in the accessibility package,
making it easy to write programs with Swing that people with disabilities can use. The design of the
accessibility package also makes it easy to add accessibility support to custom components. These
custom components can extend existing Swing components, can extend existing AWT components,
or can be lightweight components developed from scratch.
� The Swing component package ([Link]): The Swing component package is the largest of
Swing's five packages. As Swing's initial beta release drew near, the Swing component package
contained 99 classes and 23 interfaces. With a couple of exceptions, the Swing component package is
also the package that implements all the component classes used in Swing. (The exceptions
are JTableHeaderapi, implemented in the [Link] package, and JTextComponentapi,
implemented in [Link]. ) Swing's UI classes (those that have names beginning with "J")
are classes that are actually used to implement components; all other Swing classes are non-UI classes
that provide services and functionalities to applications and components. For more details, see the
section headed "Varieties of Swing classes."
� The basic package ([Link]): The basic package is the second largest package in the
Swing set. It contains around 57 classes (but no interfaces). This package defines the default look-
and-feel characteristics of Swing components. By subclassing the classes in the basic package, you
can create components with your own customized pluggable L&F designs.)
� The border package ([Link]): This package contains one interface and nine classes
that you can subclass when you want to draw a specialized border around a component. (You don't
have to touch this package when you create components with the default borders prescribed by
whatever look and feel you are using. Swing draws default borders automatically around standard
components.)
� The event package ([Link]): The event package defines Swing-specific event classes.
Its role is similar to that of the [Link] package.
20
[Link] unit III
Platform-
Architecture Platform-Dependent
Independent
Highly
Customization Less customizable
customizable
21
[Link] unit III
available available
Java Swing provides a number of advantages for developing graphical user interfaces (GUIs) in Java. Some
of the key advantages of Java Swing are
1. Platform Independence: Swing is written entirely in Java, which makes it platform-independent. It can run
on any platform that supports Java, without any modification.
2. Look and Feel: Java Swing provides a pluggable look and feels feature, which allows developers to
customize the appearance of the components. It provides a consistent look and feels across platforms, which
helps in creating a professional-looking GUI.
3. Rich Component Set: Java Swing provides a rich set of components, including advanced components like
JTree, JTable, and JSpinner. It also provides support for multimedia components, such as audio and video.
4. Layout Managers: Java Swing provides a variety of layout managers, which makes it easy to arrange the
components on a GUI. The layout managers help in creating GUIs that are visually appealing and easy to
use.
5. Event Handling: Java Swing provides a powerful and flexible event handling model, which makes it easy to
handle user events such as mouse clicks and keyboard presses. The event-handling model makes it easy to
add interactivity to the GUI.
22
[Link] unit III
6. Customizable: Java Swing components are highly customizable, which makes it easy to create GUIs that
meet the specific needs of an application. The components can be easily modified to suit the look and feel of
the application.
Method Description
We can write the code of swing inside the main(), constructor or any other method.
import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
23
[Link] unit III
File: [Link]
import [Link].*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
File: [Link]
import [Link].*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
[Link](130,100,100, 40);
24