Swing
Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-drop support.
What is JFC?
JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify
desktop Applications. Many programmers think that JFC and Swing are one and the same
thing, but that is not so. JFC contains Swing [A UI component package] and quite a number of
other items:
Cut and paste: Clipboard support.
Accessibility features: Aimed at developing GUIs for users with disabilities.
The Desktop Colors Features were first introduced in Java 1.1
Java 2D: it has Improved colors, images, and text support.
Features Of Swing Class
Pluggable look and feel.
Uses MVC architecture.
Lightweight Components
Platform Independent
Advanced features such as JTable, JTabbedPane, JScollPane, etc.
Java is a platform-independent language and runs on any client machine, the GUI look and
feel, owned and delivered by a platform-specific O/S, simply does not affect an
application’s GUI constructed using Swing components.
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend on
any non-Java [O/s based) system classes. Swing components have their own view
supported by Java’s look and feel classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the program
runs. The Swing library provides an API that gives real flexibility in determining the look
and feel of the GUI of an application
Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
Over the years, one component architecture has proven itself to be exceptionally effective:
– Model-View-Controller or MVC for short.
In MVC terminology, the model corresponds to the state information associated with the
Component.
The view determines how the component is displayed on the screen, including any aspects
of the view that are affected by the current state of the model.
The controller determines how the component reacts to the user.
o Heavyweight.
2. Lightweight Containers
o Example: JPanel
Swing JButton
JButton class provides functionality of a button. It is used to create button component. JButton
class has three constuctors,
Example of JButton
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JLabel
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon.
JLabel can display text, image or both . JLabel is only a display of text or image and it cannot
get focus . JLabel is inactive to input events such a mouse focus or keyboard focus. By default
labels are vertically centered but the user can change the alignment of label.
Constructor of the class are :
Icon
Many Swing components, such as labels, buttons, and tabbed panes, can be decorated with
an icon — a fixed-sized picture. An icon is an object that adheres to the Icon interface. Swing
provides a particularly useful implementation of the Icon interface: ImageIcon, which paints an
icon from a GIF, JPEG, or PNG image.
The program uses one image icon to contain and paint the yellow splats. One statement creates
the image icon and two more statements include the image icon on each of the two labels:
JTextField
JTextField is a part of javax.swing package. The class JTextField is a component that allows
editing of a single line of text. JTextField inherits the JTextComponent class and uses the
interface SwingConstants.
JComboBox
JCheckBox
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.
Constructor of the class are :
1. JCheckBox() : creates a new checkbox with no text or icon
2. JCheckBox(Icon i) : creates a new checkbox with the icon specified
3. JCheckBox(Icon icon, boolean s) : creates a new checkbox with the icon specified and the
boolean value specifies whether it is selected or not.
4. JCheckBox(String t) :creates a new checkbox with the string specified
5. JCheckBox(String text, boolean selected) :creates a new checkbox with the string
specified and the boolean value specifies whether it is selected or not.
6. JCheckBox(String text, Icon icon) :creates a new checkbox with the string and the icon
specified.
7. JCheckBox(String text, Icon icon, boolean selected): creates a new checkbox with the
string and the icon specified and the boolean value specifies whether it is selected or not.
RadioButtons
RadioButtons are a part of Javax package. RadioButtons are mainly used to create a series of
items where only one can be selected. When a Radio button is pressed and released an Action
event is sent, this Action Event can be handled using an Event Handler.
RadioButton can be added to Toggle Group so that the user cannot select more than one item .
By default a radio button is not a part of any toggle group. The selected item of a toggle group
can be found using getSelectedToggle() function.
Constructors of the RadioButton class:
1. RadioButton():Creates a radio button with an empty string for its label.
2. RadioButton(String t):Creates a radio button with the specified text as its label
Commonly used methods:
method explanation
setToggleGroup(ToggleGroup
sets the toggle group for the radio button
tg)
JTabbedPane
JTabbedPane is a GUI(Graphical User Interface) component in the Java Swing library that
allows you to create a tabbed pane interface. A tabbed pane is a container that can store and
organize multiple components into distinct tabs. It contains a collection of tabs. When you
click on a tab, only data related to that tab will be displayed. JTabbedPane comes under the
Java Swing package.
addTab(String title, Component Creates a new tab with the given title and
component) content.
import javax.swing.*;
import java.awt.*;
// Driver Class
public class TabbedUIExample1 {
// main function
public static void main(String[] args) {
// Run the Swing application on the Event Dispatch Thread (EDT)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Create a new JFrame (window)
JFrame window = new JFrame("JTabbedPane Example");
// Close operation when the window is closed
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close
operation when the window is closed
// Set the initial size of the window
window.setSize(400, 300);
JScrollPane
Java JScrollPane is a component in the Java Swing library that provides a scrollable view of
another component, usually a JPanel or a JTextArea. it provides a scrolling functionality to the
display for which the size changes dynamically. It is useful to display the content which exceeds
the visible area of the window. In this article, we are going to see some constructors, methods,
and examples of JScrollPane.
Constructor of JScrollPane
Constructors Descriptions
JScrollPane(int vertical, int This constructor creates an empty JScrollPane with the
horizontal) specified vertical and horizontal scrollbar.
Methods of JScrollPane
Methods Description
void setVerticalScrollBarPolicy(int
Sets the vertical scrollbar policy
vertical)
void setHorizontalScrollBarPolicy(int
Sets the horizontal scrollbar policy
horizontal)
void
setColumnHeaderView(Component sets the column header for the JScrollPane
comp)
void setRowHeaderView(Component
sets the rowheader for the JScrollPane
comp)
import javax.swing.*;
import java.awt.*;
// Driver Class
public class SimpleJScrollPaneExample {
// main function
public static void main(String[] args) {
JTree
The JTree is a type of GUI(Graphic User Interface) that displays information in a hierarchical
way. This intricate component part provides a quite elegant substance of representing
relationships among elements in a tree-like structure. In this exploration, we'll delve into the
essence of the JTree class, examining its declaration, normally used constructors and examples.
JTree Class Declaration
The JTree class is an extension of the JComponent class, inheriting its capabilities. It also
implements the Scrollable and Accessible interfaces, enhancing its functionality and
accessibility.
public class JTree extends JComponent implements Scrollable, Accessible
JTree is created with the specified TreeNode as its root. This allows you
JTree(TreeNode to define a custom structure for your tree by providing a root node
root) explicitly.
Example of Java JTree:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
Output:
JTable
The JTable class is a part of Java Swing Package and is generally used to display or edit two-
dimensional data that is having both rows and columns. It is similar to a spreadsheet. This
arranges data in a tabular form.
Constructors in JTable:
1. JTable(): A table is created with empty cells.
2. JTable(int rows, int cols): Creates a table of size rows * cols.
3. JTable(Object[][] data, Object []Column): A table is created with the specified name
where []Column defines the column names.
Functions in JTable:
1. addColumn(TableColumn []column) : adds a column at the end of the JTable.
2. clearSelection() : Selects all the selected rows and columns.
3. editCellAt(int row, int col) : edits the intersecting cell of the column number col and row
number row programmatically, if the given indices are valid and the corresponding cell is
editable.
4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position
row, col in the JTable.
Example Of JTable
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
// Constructor
JTableExamples()
{
// Frame initialization
f = new JFrame();
// Frame Title
f.setTitle("JTable Example");
// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };
// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}
// Driver method
public static void main(String[] args)
{
new JTableExamples();
}
Output:
JProgressBar
JProgressBar is a part of Java Swing package. JProgressBar visually displays the progress of
some specified task. JProgressBar shows the percentage of completion of specified task.The
progress bar fills up as the task reaches it completion. In addition to show the percentage of
completion of task, it can also display some text.
Constructors of JProgressBar :
// create a frame
static JFrame f;
static JProgressBar b;
// create a frame
f = new JFrame("ProgressBar demo");
// create a panel
JPanel p = new JPanel();
// create a progressbar
b = new JProgressBar();
b.setStringPainted(true);
// add progressbar
p.add(b);
// add panel
f.add(p);
// set the size of the frame
f.setSize(500, 500);
f.setVisible(true);
fill();
}