UNIT5 Applets and Swings
Java Applet
Applet is a special type of program that is embedded in the webpage to generate
the dynamic content. It runs inside the browser and works at client side.
Important points :
1. All applets are sub-classes (either directly or indirectly)
of [Link] class.
2. Applets are not stand-alone programs. Instead, they run within either a
web browser or an applet viewer. JDK provides a standard applet viewer
tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by [Link]().
Rather it is handled with various AWT methods, such as drawString().
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel.
Panel class extends Container which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The [Link] class 4 life cycle methods and [Link] class
provides 1 life cycle methods for an applet.
[Link] class
For creating any applet [Link] class must be inherited. It provides 4
life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet
is stop or browser is minimized.
4. paint( ) : The paint( ) method is called each time an AWT-based
applet’s output must be redrawn. This situation can occur for several
reasons.
5. public void destroy(): is used to destroy the Applet. It is invoked only
once.
[Link] class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.
//[Link]
import [Link];
import [Link];
public class Cseab extends Applet{
public void paint(Graphics g){
[Link]("Hello World", 170, 170);
}
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
How to run applet :
1. Set path where your java file available and compile javac [Link]
[Link] your html file by appletviewer [Link]
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer [Link].
Now Html file is not required but it is for testing purpose only.
//[Link]
import [Link];
import [Link];
public class Cseab extends Applet{
public void paint(Graphics g){
[Link]("Hello World", 20, 20);
}
}
/*
<html>
<TITLE> Applet </title>
<applet code=" [Link]" width="300" height="300">
</applet>
</html>
*/
Types of Applets in Java
A special type of Java program that runs in a Web browser is referred to
as Applet. It has less response time because it works on the client-side. It is
much secured executed by the browser under any of the platforms such as
Windows, Linux and Mac OS etc. There are two types of applets that a web
page can contain.
1. Local Applet
2. Remote Applet
Let's understand both types of Applet one by one:
Local Applet
Local Applet is written on our own, and then we will embed it into web pages.
Local Applet is developed locally and stored in the local system. A web page
doesn't need the get the information from the internet when it finds the local
Applet in the system. It is specified or defined by the file name or pathname.
There are two attributes used in defining an applet, i.e., the codebase that
specifies the path name and code that defined the name of the file that contains
Applet's code.
Specifying Local applet
<applet>
codebase = "tictactoe"
code = "[Link]"
width = 120
height = 120>
</applet>
Let's take an example of Local applet to understand how we can create it and
embedded it into web page.
1. First, we will create a Local Applet for embedding in a web page.
2. After that, we will add that Local Applet to the web page.
[Link]
//Import packages and classes
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
//Creating FaceApplet class that extends Applet
public class FaceApplet extends Applet
{
//paint() method starts
public void paint(Graphics g){
//Creating graphical object
[Link]([Link]);
[Link]("Welcome", 50, 50);
[Link](20, 30, 20, 300);
[Link](70, 100, 30, 30);
[Link](170, 100, 30, 30);
[Link](70, 200, 30, 30);
[Link]([Link]);
[Link](170, 200, 30, 30);
[Link](90, 150, 30, 30, 30, 270);
[Link](270, 150, 30, 30, 0, 180);
} }
Execute the above code by using the following commands:
Remote Applet
A remote applet is designed and developed by another developer. It is located or
available on a remote computer that is connected to the internet. In order to run
the applet stored in the remote computer, our system is connected to the internet
then we can download run it. In order to locate and load a remote applet, we
must know the applet's address on the web that is referred to as Uniform
Recourse Locator(URL).
Specifying Remote applet
<applet >
codebase = "[Link]
code = "[Link]"
width = 120
height =120>
</applet>
Difference Between Local Applet and Remote Applet
The following table describes the key differences between Local applet and
Remote applet.
Local Applet Remote Applet
There is no need to define the We need to define the Applet's URL in
Applet's URL in Local Applet. Remote Applet.
Local Applet is available on our Remote Applet is not available on our
computer. computer.
In order to use it or access it, we In order to use it or access it on our
don't need Internet Connection. computer, we need an Internet Connection.
It is written on our own and then It was written by another developer.
embedded into the web pages.
We don't need to download it. It is available on a remote computer, so we
need to download it to our system.
Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import [Link];
import [Link];
public class Cse extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
[Link](str,50, 50);
}
[Link]
<html>
<body>
<applet code=" [Link]" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Difference between Application and Applet
Java Application is just like a Java program that runs on an
underlying operating system with the support of a virtual machine. It is also
known as an application program.
The graphical user interface is not necessary to execute the java applications,
it can be run with or without it.
Java Applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works on the client-side. An applet is embedded
in an HTML page using the APPLET or OBJECT tag and hosted on a web
server. Applets are used to make the website more dynamic and entertaining.
The difference between Application and Applet:
Parameters Java Application Java Applet
Applets are small Java
Applications are just like
programs that are designed to
a Java program that can
be included with the HTML
Definition be executed
web document. They require a
independently without
Java-enabled web browser for
using the web browser.
execution.
The applet does not require the
The application program
main () main() method for its execution
requires a main() method
method instead init() method is
for its execution.
required.
The “javac” command is Applet programs are compiled
used to compile with the “javac” command and
Compilation
application programs, run using either the
which are then executed “appletviewer” command or
Parameters Java Application Java Applet
using the “java” the web browser.
command.
Java application programs
have full access to the Applets don’t have local disk
File access
local file system and and network access.
network.
Applets can only access
Applications can access
browser-specific services. They
Access level all kinds of resources
don’t have access to the local
available on the system.
system.
First and foremost, the
installation of a Java The Java applet does not need
Installation
application on the local to be installed beforehand.
computer is required.
Applications can execute Applets cannot execute
Execution the programs from the programs from the local
local system. machine.
An application program is An applet program is needed to
Program needed to perform some perform small tasks or part of
tasks directly for the user. them.
It cannot start on its own, but it
It cannot run on its own; it
Run can be executed using a Java-
needs JRE to execute.
enabled web browser.
Connection Connectivity with other It is unable to connect to other
with servers servers is possible. servers.
Read and It supports the reading It does not support the reading
Write and writing of files on the and writing of files on the local
Operation local computer. computer.
Parameters Java Application Java Applet
Executed in a more restricted
Application can access
environment with tighter
the system’s data and
Security security. They can only use
resources without any
services that are exclusive to
security limitations.
their browser.
Java applications are self-
Applet programs cannot run on
contained and require no
Restrictions their own, necessitating the
additional security
maximum level of security.
because they are trusted.
Java Swing
Java Swing 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 [Link] package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Java Swing Packages
Some of the commonly used packages in Java Swing are:
1. [Link]: This package contains the core components of Swing, such as
JButton, JLabel, JTable, JList, and many more. It also contains the classes for
creating top-level containers such as JFrame and JDialog.
2. [Link]: This package contains the classes for handling events
generated by the Swing components. It includes event listener interfaces, event
adapter classes, and event objects.
3. [Link]: This package contains the classes for creating and managing
tables in Swing. It includes the classes for creating JTable, TableModel,
TableColumn, and TableCellRenderer.
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 are platform- Java swing components
dependent. are platform-independent.
2) AWT components are heavyweight. Swing components
are lightweight.
3) AWT doesn't support pluggable look Swing supports pluggable
and feel. look and feel.
4) AWT provides less components than Swing provides more
Swing. powerful components such as
tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model represents
data, view represents presentation and
controller acts as an interface between
model and view.
Limitations of AWT
The buttons of AWT does not support pictures.
It is heavyweight in nature.
Two very important components trees and tables are not present.
Extensibility is not possible as it is platform dependent
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
Many programmers think that JFC and Swing are one and the same thing, but
that is not so.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
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 component.
setLayout(LayoutManager m)
public void setVisible(boolean b) sets the visibility of the component. It is
by default false.
MVC Architecture in Java
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information. The MVC pattern needs all these components to be separated as
different objects.
In this section, we will discuss the MVC Architecture in Java, alongwith its
advantages and disadvantages and examples to understand the implementation
of MVC in Java.
What is MVC architecture in Java?
The model designs based on the MVC architecture follow MVC design pattern.
The application logic is separated from the user interface while designing the
software using model designs.
The MVC pattern architecture consists of three layers:
o Model: It represents the business layer of application. It is an object to
carry the data that can also contain the logic to update controller if data is
changed.
o View: It represents the presentation layer of application. It is used to
visualize the data that the model contains.
o Controller: It works on both the model and view. It is used to manage
the flow of application, i.e. data flow in the model object and to update
the view whenever data is changed.
In Java Programming, the Model contains the simple Java classes, the View
used to display the data and the Controller contains the servlets. Due to this
separation the user requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side, for
a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
Advantages of MVC Architecture
The advantages of MVC architecture are as follows:
o MVC has the feature of scalability that in turn helps the growth of
application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of
code.
o The developers can work with the three layers (Model, View, and
Controller) simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not
require to deal with massive code.
o The extending and testing of application is easier.
Implementation of MVC using Java
To implement MVC pattern in Java, we are required to create the following
three classes.
o Employee Class, will act as model layer
o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer
MVC Architecture Layers
Model Layer
The Model in the MVC design pattern acts as a data layer for the application. It
represents the business logic for application and also the state of application.
The model object fetch and store the model state in the database. Using the
model layer, rules are applied to the data that represents the concepts of
application.
View Layer
As the name depicts, view represents the visualization of data received from the
model. The view layer consists of output of application or user interface. It
sends the requested data to the client, that is fetched from model layer by
controller.
Controller Layer
The controller layer gets the user requests from the view layer and processes
them, with the necessary validations. It acts as an interface between Model and
View. The requests are then sent to model for data processing. Once they are
processed, the data is sent back to the controller and then displayed on the view.
Swing Components
A component is an independent visual control and Java Swing Framework
contains a large set of these components which provide rich functionalities and
allow high level of customization.
They all are derived from JComponent class. All these components are
lightweight components. This class provides some common functionality like
pluggable look and feel, support for accessibility, drag and drop, layout, etc.
Some of the important and common components of the Java Swing class are:
class Description
A Component is the Abstract base class for about the
non-menu user-interface controls of Java SWING.
Component
Components are representing an object with a graphical
representation.
A Container is a component that can container Java
Container
SWING Components
A JComponent is a base class for all swing UI
Components In order to use a swing component that
JComponent inherits from JComponent, the component must be in a
containment hierarchy whose root is a top-level Java
Swing container.
A JLabel is an object component for placing text in a
JLabel
container.
JButton This class creates a labeled button.
JColorChooser A JColorChooser provides a pane of controls designed to
allow the user to manipulate and select a color.
JCheckBox A JCheckBox is a graphical (GUI) component that can
class Description
be in either an on-(true) or off-(false) state.
The JRadioButton class is a graphical (GUI) component
JRadioButton that can be in either an on-(true) or off-(false) state. in
the group
A JList component represents the user with the scrolling
JList
list of text items.
A JComboBox component is Presents the User with a
JComboBox
show up Menu of choices.
A JTextField object is a text component that will allow
JTextField
for the editing of a single line of text.
JPasswordField A JPasswordField object it is a text component
specialized for password entry.
A JTextArea object is a text component that allows for
JTextArea
the editing of multiple lines of text.
A ImageIcon control is an implementation of the Icon
Imagelcon
interface that paints Icons from Images
A JScrollbar control represents a scroll bar component in
JScrollbar
order to enable users to Select from range values.
class Description
JOptionPane provides set of standard dialog boxes that
JOptionPane
prompt users for a value or Something.
A JFileChooser it Controls represents a dialog window
JFileChooser
from which the user can select a file.
As the task progresses towards completion, the progress
JProgressBar
bar displays the tasks percentage on its completion.
A JSlider this class is letting the user graphically (GUI)
JSlider select by using a value by sliding a knob within a
bounded interval.
A JSpinner this class is a single line input where the
JSpinner field that lets the user select by using a number or an
object value from an ordered sequence.
Containers
A container holds a group of components. It provides a space where a
component can be managed and displayed. Containers are of two types:
1. Top level Containers
It inherits Component and Container of AWT.
It cannot be contained within other containers.
Heavyweight.
Example: JFrame, JDialog, JApplet
2. Lightweight Containers
It inherits JComponent class.
It is a general purpose container.
It can be used to organize related components together.
Example: JPanel
JFrame
The [Link] class is a type of container which inherits the
[Link] class. JFrame works like the main window where components
like labels, buttons, textfields are added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help
of setDefaultCloseOperation(int) method.
Fields
Modifier and Type Field Description
protected accessibleContext The accessible context
AccessibleContext property.
static int EXIT_ON_CLOSE The exit application default
window close operation.
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other
method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding
it on the JFrame object inside the main() method.
File: [Link]
import [Link].*;
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
[Link](130,100,100, 40);//x axis, y axis, width, height
[Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500 height
[Link](null);//using no layout managers
[Link](true);//making the frame visible
}}
Swing Applet
Approach to Using Swing Applet in Java
We need to import the packages for Swing and AWT Components.
Once the packages are imported, we need to create the class that
implements the ActionListener interface.
Then we need to initialize all the required GUI components like labels,
buttons, and input fields.
We will create the JPanel to align and arrange all the GUI components in
the Grid layout.
Then we will set up the event listener for registering the applet as the
action listener for the Multiply button.
We will handle the button click in the actionPerformed method to perform
the multiply operation and show the result.
We will make the HTML file to run the applet.
We have to compile the Java code using Javac and then we need to run
using appletviewer.
Steps for Creating and Running the Swing Applet
Step 1: First, create the file as [Link] and enter the code into it.
Step 2: Once the code is been inserted then we need to create the
[Link] file, through which we will display the output.
<!DOCTYPE html>
<html>
<head>
<title>Java Applet Example</title>
</head>
<body>
<applet code="[Link]" width=220 height=90>
No Support
</applet>
</body>
</html>
Step 3: Then we need to compile the Java code using the below command:
javac [Link]
Step 4: Now finally we need to run the application using the below power:
appletviewer [Link]
// Java Program for Using Swing Applet in Java
import [Link].*;
import [Link].*;
import [Link].*;
// Defining a class named SApplet that extends JApplet and
// implements the ActionListener interface
public class SApplet extends JApplet implements ActionListener {
JTextField num1, num2, res;
JButton resBtn;
// This is Initialization method for the applet
public void init()
{
// Creating three text fields for number input and
// one button for calculation result
num1 = new JTextField(5);
num2 = new JTextField(5);
res = new JTextField(10);
// Make the result field non-editable
[Link](false);
resBtn = new JButton("Multiply");
// Register this applet as the action
// listener for the button
[Link](this);
// Creating labels for the input fields and result
JLabel l1 = new JLabel("Enter Number 1:");
JLabel l2 = new JLabel("Enter Number 2:");
JLabel l3 = new JLabel("Result:");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
// Creating a JPanel to arrange
// components in a grid layout
JPanel pan = new JPanel();
[Link](new GridLayout(4, 2));
// Adding labels, input fields, button, and empty
// label for spacing
[Link](l1);
[Link](num1);
[Link](l2);
[Link](num2);
// Set button background color
[Link]([Link]);
[Link](resBtn);
// Empty label for spacing
[Link](new JLabel());
[Link](l3);
[Link](res);
// Set text color Customize the fonts of various
// components
[Link]([Link]);
Font lfont = [Link]();
// Creating a new font with size 20
Font inFont = [Link]([Link], 20);
[Link](inFont);
[Link](inFont);
[Link](inFont);
[Link](inFont);
[Link](inFont);
[Link](inFont);
[Link](inFont);
// Set the layout of the applet to BorderLayout and
// add the JPanel to the center
setLayout(new BorderLayout());
add(pan, [Link]);
}
// ActionListener method to handle button clicks
public void actionPerformed(ActionEvent e){
// Check if the event source is the Multiply button
if ([Link]() == resBtn) {
String str1 = [Link]();
String str2 = [Link]();
try {
int num1 = [Link](str1);
int num2 = [Link](str2);
int result = num1 * num2;
// Display the result in result text field
[Link]([Link](result));
}
catch (NumberFormatException ex) {
// Display an error message for invalid input
[Link]("Wrong Input");
}
}
}
}
JComponent
The JComponent class is the base class of all Swing components except top-
level containers. Swing components whose names begin with "J" are
descendants of the JComponent class. For example, JButton, JScrollPane,
JPanel, JTable etc. But, JFrame and JDialog don't inherit JComponent class
because they are the child of top-level containers.
The JComponent class extends the Container class which itself extends
Component. The Container class has support for adding components to the
container.
Useful Methods
Method Description
setActionMap(ActionMap am) It sets the ActionMap to am.
setBackground(Color bg) It sets the background color of this
component.
setFont(Font font) It sets the font for this component.
setMaximumSize(Dimension It sets the maximum size of this
maximumSize) component to a constant value.
setMinimumSize(Dimension It sets the minimum size of this
minimumSize) component to a constant value.
setUI(ComponentUI newUI) It sets the look and feel delegate for
this component.
setVisible(boolean aFlag) It makes the component visible or
invisible.
setForeground(Color fg) It sets the foreground color of this
component.
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 [Link] 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.
Commonly used Methods of AbstractButton class:
Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the
button.
void It is used to add the action listener to this
addActionListener(ActionListener a) object.
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
Let's see the declaration for [Link] class.
public class JLabel extends JComponent implements SwingConstants, Accessi
ble
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 specified
horizontalAlignment) text, image, and horizontal alignment.
Commonly used Methods:
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component
will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along
alignment) the X axis.
Icon getIcon() It returns the graphic image that the label
displays.
int getHorizontalAlignment() It returns the alignment of the label's contents
along the X axis.
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
Let's see the declaration for [Link] class.
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 Creates a new TextField initialized with the
columns) specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.
Commonly used Methods:
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action
listener to receive action events from
this textfield.
Action getAction() It returns the currently set Action for
this ActionEvent source, or null if no
Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener It is used to remove the specified
l) action listener so that it no longer
receives action events from this
textfield.
Program:
import [Link].*;
public class ButtonLableExample {
public static void main (String[ ] args) {
// create instance of frame with the label
JFrame f = new JFrame("ButtonLable Example");
// create instance of button with label
JButton b = new JButton("SUBMIT");
// set the position for the button in frame
[Link](300,300,80,30);
// add button to the frame
[Link](b);
// initializing the labels
JLabel s1 = new JLabel ("Username :");
JLabel s2= new JLabel (" Password :");
// set the location of label
[Link](50, 100, 100, 30);
[Link](50, 150, 100, 30);
// adding labels to the frame
[Link](s1);
[Link](s2);
// instantiating the textfield objects
JTextField t1 = new JTextField("user name is cseab");
// setting the location of those objects in the frame
[Link](170, 100, 200, 30);
JTextField t2 = new JTextField("cseab@123");
[Link](170, 150, 200, 30);
// adding the components to frame
[Link](t1);
[Link](t2);
// set size, layout and visibility of frame
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
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
Let's see the declaration for [Link] class.
public class JCheckBox extends JToggleButton implements Accessible
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
JCheckBox Example: Food Order
import [Link].*;
import [Link].*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");
[Link](50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
[Link](100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
[Link](100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
[Link](100,200,150,20);
b=new JButton("Order");
[Link](100,250,80,30);
[Link](this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if([Link]()){
amount+=100;
msg="Pizza: 100\n";
}
if([Link]()){
amount+=30;
msg+="Burger: 30\n";
}
if([Link]()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
[Link](this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample();
}
}
Output:
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.
import [Link].*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
[Link](75,50,100,30);
[Link](75,100,100,30);
ButtonGroup bg=new ButtonGroup();
[Link](r1);[Link](r2);
[Link](r1);[Link](r2);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:
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.
import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
JTabbedPane
The JTabbedPane class is used to switch between a group of components by
clicking on a tab with a given title or icon. It inherits JComponent class.
Program:
import [Link].*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
[Link](ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
[Link](50,50,200,200);
[Link]("main",p1);
[Link]("visit",p2);
[Link]("help",p3);
[Link](tp);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
Output:
JScrollPane
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 [Link];
import [Link];
import [Link];
import [Link];
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.
[Link](500, 500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
[Link]().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
[Link]([Link]
NTAL_SCROLLBAR_ALWAYS);
[Link]([Link]
_SCROLLBAR_ALWAYS);
[Link]().add(scrollableTextArea);
}
public static void main(String[] args) {
[Link](new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Output:
JTree
The JTree class is used to display the tree structured data or hierarchical data.
JTree is a complex component. It has a 'root node' at the top most which is a
parent for all nodes in the tree. It inherits JComponent class.
import [Link].*;
import [Link];
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
[Link](color);
[Link](font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
[Link](red); [Link](blue); [Link](black); [Link](green);
JTree jt=new JTree(style);
[Link](jt);
[Link](200,200);
[Link](true);
}
public static void main(String[] args) {
new TreeExample();
}
Output:
JTable
The JTable class is used to display data in tabular form. It is composed of rows
and columns.
import [Link].*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
[Link](30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
[Link](sp);
[Link](300,400);
[Link](true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output: