0% found this document useful (0 votes)
24 views

Unit 5 Swings

Uploaded by

Lakshmi G
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit 5 Swings

Uploaded by

Lakshmi G
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT 5

Java Swing Tutorial


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
There are many differences between java awt and swing that are given
below.

No. Java AWT Java Swing

1) AWT components Java swing components


are platform-dependent. are platform-independent.

2) AWT components Swing components


are heavyweight. are lightweight.
3) AWT doesn't support Swing supports pluggable
pluggable look and feel. look and feel.
4) AWT provides less Swing provides more powerful
components than Swing. components such as tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows Swing follows MVC.


MVC(Model View Controller)
where model represents
data, view represents
presentation and controller
acts as an interface
between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.
Components and Containers:

A Swing GUI consists of two key items: 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.
Components:

In general, Swing components are derived from the JComponent class. JComponent
provides the functionality that is common to all components. For example, JComponent
supports the pluggable look and feel. JComponent inherits the AWT classes Container
and Component.
Containers:

Swing defines two types of containers.

1. Top-level containers/ Root containers: JFrame, JApplet,JWindow, and JDialog. As


the name implies, a top-level container must be at the top of a containment
hierarchy.
A top-level container is not contained within any other container. Furthermore, every
containment hierarchy must begin with a top-level container.
The one most commonly used for applications are JFrame and JApplet.
Unlike Swing’s other components , the top-level containers are heavyweight.
Because they inherit AWT classes Component and Container.
Whenever we create a top level container four sub-level containers are
automatically created:

Glass pane (JGlass)


Root pane (JRootPane)
Layered pane(JLayeredPane)
Content pane

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 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.

2. Lightweight containers – containers do inherit JComponent. An example of


a lightweight container is JPanel, which is a general-purpose container.
Lightweight

containers are often used to organize and manage groups of related


components.
JFrame:

We know 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 fram, 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)

where constant values are


Example:

import javax.swing.*;

class FrameDemo

public static void main(String arg[])

JFrame jf=new JFrame("PVPSIT");

jf.setSize(200,200);

jf.setVisible(true);

jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE );

}
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.
APPLETS

A Java applet is a special kind of Java program that a browser enabled with
Java technology can download from the internet and run. An applet is
typically embedded inside a web page and runs in the context of a
browser. An applet must be a subclass of the java.applet.Applet class. The
Applet class provides the standard interface between the applet and the
browser environment.

The Applet class is contained in the java.applet package.Applet contains


several methods that give you detailed control over the execution of your
applet.

In addition,java.applet package also defines three interfaces:


AppletContext, AudioClip, and AppletStub.
Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another


component.
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the
component. It is by default false.
Java Swing Examples
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.

Simple Java Swing Example


import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
MVC architecture

MVC (Model-View-Controller) is a pattern in software design commonly used to


implement user interfaces, data, and controlling logic. It emphasizes a separation
between the software's business logic and display. This "separation of concerns"
provides for a better division of labor and improved maintenance
Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the
following three parts −
Model − The lowest level of the pattern which is responsible for maintaining data.
View − This is responsible for displaying all or a portion of the data to the user.
Controller − Software Code that controls the interactions between the Model and View.
MVC is popular as it isolates the application logic from the user interface layer and
supports separation of concerns. Here the Controller receives all requests for the
application and then works with the Model to prepare any data needed by the View.
The View then uses the data prepared by the Controller to generate a final presentable
response.
The Model
The model is responsible for managing the data of the application. It responds to the
request from the view and it also responds to instructions from the controller to
update itself.
The View
It means presentation of data in a particular format, triggered by a controller's
decision to present the data. They are script-based templating systems like JSP, ASP,
PHP and very easy to integrate with AJAX technology.
The Controller
The controller is responsible for responding to the user input and perform
interactions on the data model objects. The controller receives the input, it validates
the input and then performs the business operation that modifies the state of the
data model.
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text


and icon.
JButton(String s) It creates a button with the
specified text.
JButton(Icon i) It creates a button with the
specified icon object.
Java JButton Example

import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example"
);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used
to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly. It inherits JComponent class.
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no


image and with an empty string
for the title.
JLabel(String s) Creates a JLabel instance with the
specified text.
JLabel(Icon i) Creates a JLabel instance with the
specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the
horizontalAlignment) specified text, image, and
horizontal alignment.
Java JLabel Example

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
JTextField class declaration

public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField


JTextField(String text) Creates a new TextField initialized
with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized
with the specified text and
columns.
JTextField(int columns) Creates a new empty TextField
with the specified number of
columns.
Java JTextField Example

import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");

JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.")
;
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off"
to "on ".It inherits JToggleButton class.
JCheckBox class declaration
public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected


check box button with no text, no
icon.
JChechBox(String s) Creates an initially unselected
check box with text.
JCheckBox(String text, boolean Creates a check box with text and
selected) specifies whether or not it is
initially selected.
JCheckBox(Action a) Creates a check box where
properties are taken from the
Java JCheckBox Example

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton class declaration
public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio


button with no text.
JRadioButton(String s) Creates an unselected radio
button with specified text.
JRadioButton(String s, boolean Creates a radio button with the
selected) specified text and selected status.
Java JRadioButton Example

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();
}
}
Java JList

The object of JList class represents a list of text items. The list of text items can be set
up so that the user can choose either one item or multiple items. It inherits
JComponent class.
JList class declaration

public class JList extends JComponent implements Scrollable, Accessible


Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty,


read-only, model.
JList(ary[] listData) Creates a JList that displays the
elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays
elements from the specified, non-
null, model.
Java JList Example
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits JComponent class.
JComboBox class declaration
public class JComboBox extends JComponent implements ItemSelectable, ListDataList
ener, ActionListener, Accessible
Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a


default data model.
JComboBox(Object[] items) Creates a JComboBox that
contains the elements in the
specified array.
JComboBox(Vector<?> items) Creates a JComboBox that
contains the elements in the
specified Vector.
Java JComboBox Example
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzea
land"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
APPLETS

A Java applet is a special kind of Java program that a browser enabled


with Java technology can download from the internet and run. An applet
is typically embedded inside a web page and runs in the context of a
browser. An applet must be a subclass of the java.applet.Applet class.
The Applet class provides the standard interface between the applet and
the browser environment.

The Applet class is contained in the java.applet package.Applet contains


several methods that give you detailed control over the execution of your
applet.

In addition,java.applet package also defines three interfaces:


AppletContext, AudioClip, and AppletStub.
Applet Basics:

All applets are subclasses of Applet. Thus, all applets must import java.applet.
Applets must also import java.awt. AWT stands for the Abstract Window Toolkit.
Since all applets run in a window, it is necessary to include support for that
window by importing java.awt package.

Applets are not executed by the console-based Java run-time interpreter. Rather,
they are executed by either a Web browser or an applet viewer.

Execution of an applet does not begin at main( ). Output to your applet’s


window is not performed by System.out.println( ). Rather, it is handled with
various AWT methods, such as drawString( ), which outputs a string to a specified
X,Y location. Input is also handled differently than in an application.

Once an applet has been compiled, it is included in an HTML file using theAPPLET
tag. The applet will be executed by a Java-enabled web browser when it
encounters the APPLET tag within the HTML file.
To view and test an applet more conveniently, simply include a comment at the
head of your
Java source code file that contains the APPLET tag.
Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet
in a window that is 200 pixels wide and 60 pixels high. Since the
inclusion of an APPLET command makes testing applets easier, all of the
applets shown in this tutorial will contain the appropriate APPLET tag
embedded in a comment.
Applet Architecture:

An applet is a window-based program. As such, its architecture is different


from the so-called normal, console-based programs .
First, applets are event driven. it is important to understand in a general way
how the event- driven architecture impacts the design of an applet.
Here is how the process works. An applet waits until an event occurs. The AWT
notifies the applet about an event by calling an event handler that has been
provided by the applet. Once this happens, the applet must take appropriate
action and then quickly return control to the AWT.
Applet Life Cycle in Java
In Java, an applet is a special type of program embedded in the web page to
generate dynamic content. Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is created,
started, stopped, and destroyed during the entire execution of its application. It
basically has five core methods namely init(), start(), stop(), paint() and
destroy().These methods are invoked by the browser to execute.
Along with the browser, the applet also works on the client side, thus having less
processing time.
Methods of Applet Life Cycle
init(): The init() method is the first method to run that initializes the applet. It can
be invoked only once at the time of initialization. The web browser creates the
initialized objects, i.e., the web browser (after checking the security settings) runs
the init() method within the applet.
start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time the
browser is loaded or refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from one tab to another in
the browser. It is in an inactive state until the init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that
page, the start() method is invoked again.
destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the
webpage is closed. It removes the applet object from memory and is executed only
once. We cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the
start() method and when the browser or applet windows are resized.
Sequence of method execution when an applet is executed:
init()
start()
paint()
Sequence of method execution when an applet is executed:
stop()
destroy()
Applet Life Cycle Working
• The Java plug-in software is responsible for managing the life cycle of an
applet.
• An applet is a Java application executed in any web browser and works on the
client-side. It doesn't have the main() method because it runs in the browser. It
is thus created to be placed on an HTML page.
• The init(), start(), stop() and destroy() methods belongs to
the applet.Applet class.
• The paint() method belongs to the awt.Component class.
• In Java, if we want to make a class an Applet class, we need to extend
the Applet
• Whenever we create an applet, we are creating the instance of the existing
Applet class. And thus, we can use all the methods of that class.
// Using the Status Window.
import java.awt.*;
import java.applet.*;

/*<applet code="StatusWindow" width=300


height=300></applet>*/
public class StatusWindow extends Applet
{
public void init()
{setBackground(Color.cyan);
}

// Display msg in applet window. public void paint(Graphics g)


{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
Output:

You might also like