Java Unit-5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

UNIT-5

UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.

Applets
Concepts of Applets
Applet is a special type of program that is embedded in the webpage to generate dynamic
content. It runs inside the browser and works on the client side.
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone
programs. Instead, they run within either a web browser or an applet viewer. were created
with the standard applet viewer, called appletviewer, provided by the JDK. But we can use
any applet viewer or browser we like. Execution of an applet does not begin at main( ).
Output to our applet’s window is not performed by System.out.println( ).Rather, in non-
Swing applets, the output 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 a
console application.
To use an applet, it is specified in an HTMLfile. One way to do this is by using the APPLET
tag. The applet will be executed by a Java-enabled web browser when it encounters the
APPLET tag within the HTMLfile. 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.
You can test the compiled applet by starting the applet viewer with your Java source code file
specified as the target.
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.
Advantage of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• It is Secured
• It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.
Java Applet Features
• Java applet is a small and easy-to-write Java program.
• One can easily install Java applet along with various HTML documents.
• One needs a web browser (Java based) to use applets.
• Applet do not have access to the network or local disk and can only access
browser-specific services.
• It cannot perform system operations on local machines.
• Java applet cannot establish access to local system.

Prepared by Prof. Dr. Syeda Husna


Hierarchy of Applet

Differences Between Applets and Applications


Parameters Java Application Java Applet

Meaning A Java Application also known as The Java applet works on the client
application program is a type of side, and runs on the browser and
program that independently makes use of another application
executes on the computer. program so that we can execute it.

Requirement Its execution starts with the main( ) It does not require the use of any
of main( ) method only. The use of the main( ) main() method. Java applet initializes
method is mandatory. through init( ) method.

Execution It cannot run independently, but It cannot start independently but


requires JRE to run. requires APIs for use (Example. APIs
like Web API).

Installation We need to install the Java Java applet does not need to be pre-
application first and obviously on installed.
the local computer.

Connectivity It is possible to establish It cannot establish connection to other


with server connections with other servers. servers.

Operation It performs read and write tasks on It cannot run the applications on any
a variety of files located on a local local computer.
computer.

File access It can easily access a file or data It cannot access the file or data found
available on a computer system or on any local system or computer.
device.

Security Java applications are pretty trusted, Java applets are less reliable. So, they
and thus, come with no security need to be safe.

Prepared by Prof. Dr. Syeda Husna


concerns.

Life Cycle Of An 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 java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
life cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet 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. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. 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.
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.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome",150,150);
7. }
8. }
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Prepared by Prof. Dr. Syeda Husna


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 First.java. Now Html file is not
required but it is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome to applet",150,150);
7. }
8. }
9. /*
10. <applet code="First.class" width="300" height="300">
11. </applet>
12. */
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Types of Applets
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.
• Local Applets:
They are developed and stored locally, and therefore do not require an Internet
connection to be located because the directory is located on the local system.

Prepared by Prof. Dr. Syeda Husna


• Remote Applets:
Remote applets are stored in a remote computer and an Internet connection is needed
to access them. The remote applet is designed and developed by other developers. To
find and load a remote applet, you need to know the address of the network applet,
i.e., the Uniform Resource Locator (URL).

Creating Applets
Example program:
import java.applet.*;
import java.awt.*;
/*<applet code="Apppletlifecycle.class" width=200 height=200>
</applet>*/
public class Apppletlifecycle extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
public void paint(Graphics g)
{
g.drawString("welcome to applet program",50,50);
}
}
Output:

Prepared by Prof. Dr. Syeda Husna


Passing Parameters To Applets

To pass parameters to an applet in Java, you can use the param tag in the HTML file that
embeds the applet. The param tag takes two attributes: name and value. The name attribute
specifies the name of the parameter, and the value attribute specifies the value of the
parameter.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 java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Swing – Introduction
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.

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:

Prepared by Prof. Dr. Syeda Husna


1. JFC components are light-weight: Means they utilize minimum resources.
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 javax.swing.*;
Here x represents that it is an ‘extended package’ whose classes are derived from
AWT package.

Limitations of AWT:

1. Limited Customization: Compared to more modern GUI libraries like JavaFX, AWT
offers limited customization options for GUI components. It can be challenging to achieve
sophisticated visual designs without relying on platform-specific features.

2. Lack of Modern Features: As one of the earliest GUI libraries in Java, AWT lacks some
of the modern features found in later frameworks like JavaFX. For instance, it doesn’t
support hardware acceleration, which can impact graphical performance.

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.

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:

• 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.
• View: It represents the presentation layer of application. It is used to visualize the data
that the model contains.

Prepared by Prof. Dr. Syeda Husna


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

Prepared by Prof. Dr. Syeda Husna


Exploring Swing

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components.
Swing provides a rich set of widgets and packages to make sophisticated GUI components for
Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java
GUI programing that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java simple GUI programming components
like button, textbox, etc., from the library and do not have to create the components from
scratch.

Java Swing class Hierarchy Diagram

What is a Container Class?


Container classes are classes that can have other components on it. So for creating a Java
Swing GUI, we need at least one container object. There are 3 types of Java Swing
containers.

1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel
is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has
to be displayed. It is not a fully functioning window like the Frame.

Difference between AWT and Swing

Prepared by Prof. Dr. Syeda Husna


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look
and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

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 setLayout(LayoutManager sets the layout manager for the component.
m)

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Applet class.

Prepared by Prof. Dr. Syeda Husna


Example of EventHandling in JApplet:
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8. tf=new JTextField();
9. tf.setBounds(30,40,150,20);
10. b=new JButton("Click");
11. b.setBounds(80,150,70,40);
12. add(b);add(tf);
13. b.addActionListener(this);
14. setLayout(null);
15. }
16. public void actionPerformed(ActionEvent e){
17. tf.setText("Welcome");
18. }
19. }
In the above example, we have created all the controls in init() method because it is invoked only once.

myapplet.html

1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

A Java applet is a small program that is intended to be embedded within web pages and run in
the context of a web browser. JApplet is a specific class that extends Java applet and provides
support for Swing.

Here are some other differences between applets and JApplets:

• Technology: Applets are AWT, while JApplets are Swing.

Prepared by Prof. Dr. Syeda Husna


• Components: Applets use AWT components for the GUI, while JApplets allow the
use of Swings components on an applet.
• Environment: JApplets expect to be embedded in a page and used in a viewing
environment that provides it with resources.

JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame 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.

Nested Class

Modifier Class Description


and Type

protected JFrame.AccessibleJFrame This class implements accessibility support for


class the JFrame class.

Fields

Modifier and Field Description


Type

protected accessibleContext The accessible context property.


AccessibleContext

static int EXIT_ON_CLOSE The exit application default window close


operation.

protected rootPane The JRootPane instance that manages the


JRootPane contentPane and optional menuBar for this
frame, as well as the glassPane.

protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will
be forwarded to the contentPane.

Prepared by Prof. Dr. Syeda Husna


Constructors

Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration It creates a Frame in the specified GraphicsConfiguration of


gc) a screen device and a blank title.

JFrame(String title) It creates a new, initially invisible Frame with the specified
title.

JFrame(String title, It creates a JFrame with the specified title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen device.

JFrame Example
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5. JButton b=new JButton("click");//creating instance of JButton
6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
7. f.add(b);//adding button in JFrame
8. f.setSize(400,500);//400 width and 500 height
9. f.setLayout(null);//using no layout managers
10. f.setVisible(true);//making the frame visible
11. }
12. }

Output:

Prepared by Prof. Dr. Syeda Husna


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

Java JComponent Example


1. import java.awt.Color;
2. import java.awt.Graphics;
3. import javax.swing.JComponent;
4. import javax.swing.JFrame;
5. class MyJComponent extends JComponent {
6. public void paint(Graphics g) {
7. g.setColor(Color.green);
8. g.fillRect(30, 30, 100, 100);
9. }
10. }
11. public class JComponentExample {
12. public static void main(String[] arguments) {
13. MyJComponent com = new MyJComponent();
14. // create a basic JFrame
15. JFrame.setDefaultLookAndFeelDecorated(true);
16. JFrame frame = new JFrame("JComponent Example");
17. frame.setSize(300,200);
18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19. // add the JComponent to main frame
20. frame.add(com);
21. frame.setVisible(true);
22. }
23. }

Output:

Prepared by Prof. Dr. Syeda Husna


JIcon:

To add an icon to a button in Java Swing, you can use the Icon class. The Icon class allows
you to add an image to a button. Here is an example:
Icon icon = new ImageIcon("E:\editicon. PNG");
JButton button7 = new JButton(icon);

In this example, we have set the icon for button7.

You can also add an icon to a frame in Java Swing. To do this, you can use the
setIconImage() method. The setIconImage() method takes an Image object as its
argument. Here is an example:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
frame.setIconImage(img);

In this example, we have set the icon for the frame.

You can also add an icon to a label in Java Swing. To do this, you can use the setIcon()
method. The setIcon() method takes an Icon object as its argument. Here is an example:
Icon icon = new ImageIcon("E:\editicon. PNG");
JLabel label7 = new JLabel(“Warning”);

Prepared by Prof. Dr. Syeda Husna


Here, we have a warning label with an image.

Example program:

import javax.swing.*;

public class Example {

public Example() {
JFrame frame = new JFrame();
JLabel label = new JLabel(“Warning”);

// Create an ImageIcon object


ImageIcon imageIcon = new ImageIcon("image.png");

// Set the label's icon


label.setIcon(imageIcon);

// Add the label to the frame


frame.add(label);

// Set the frame's size and visibility


frame.setSize(300, 300);
frame.setVisible(true);
}

public static void main(String[] args) {


new Example();
}
}

Prepared by Prof. Dr. Syeda Husna


Output:

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 javax.swing.JLabel class.

1. 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 specified text, image,
horizontalAlignment) and horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

Prepared by Prof. Dr. Syeda Husna


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 the X
alignment) 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.

Java JLabel Example


1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

Output:

Prepared by Prof. Dr. Syeda Husna


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 javax.swing.JTextField class.

1. 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 specified text and
columns) columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:

Methods Description

void It is used to add the specified action listener to receive


addActionListener(ActionListener l) 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 It is used to remove the specified action listener so


removeActionListener(ActionListener that it no longer receives action events from this

Prepared by Prof. Dr. Syeda Husna


l) textfield.

JTextField Example
1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

Output:

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.

Prepared by Prof. Dr. Syeda Husna


1. 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 addActionListener(ActionListener It is used to add the action listener to this object.


a)

Java JButton Example


1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");

Prepared by Prof. Dr. Syeda Husna


6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Output:

Java JButton Example with ActionListener


1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }

Prepared by Prof. Dr. Syeda Husna


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 javax.swing.JCheckBox class.

1. 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, Creates a check box with text and specifies whether or not it
boolean selected) is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

Commonly used Methods:

Methods Description

Prepared by Prof. Dr. Syeda Husna


AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox Example


1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:

Prepared by Prof. Dr. Syeda Husna


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

Let's see the declaration for javax.swing.JRadioButton class.

1. 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 specified text and
selected) selected status.

Commonly used Methods:

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.

Prepared by Prof. Dr. Syeda Husna


void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton Example


1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }

Output:

Prepared by Prof. Dr. Syeda Husna


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

Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListData


Listener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] Creates a JComboBox that contains the elements in the


items) specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the


items) specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is


editable.

void It is used to add the ActionListener.


addActionListener(ActionListener a)

Prepared by Prof. Dr. Syeda Husna


void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

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.

Prepared by Prof. Dr. Syeda Husna


JTabbedPane class declaration

Let's see the declaration for javax.swing.JTabbedPane class.

1. public class JTabbedPane extends JComponent implements Serializable, Accessible,


SwingConstants

Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab


placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.

Java JTabbedPane Example


1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);

Prepared by Prof. Dr. Syeda Husna


18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}

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.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when present,


sets the scroll pane's client. The two int parameters, when present,
JScrollPane(Component) set the vertical and horizontal scroll bar policies (respectively).

JScrollPane(int, int)

JScrollPane(Component,
int, int)

Prepared by Prof. Dr. Syeda Husna


Useful Methods

Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll


pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and
Component getCorner(String) must be one of the following constants
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5. public class JScrollPaneExample {
6. private static final long serialVersionUID = 1L;
7. private static void createAndShowGUI() {
8. // Create and set up the window.
9. final JFrame frame = new JFrame("Scroll Pane Example");
10. // Display the window.
11. frame.setSize(500, 500);
12. frame.setVisible(true);
13. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. // set flow layout for the frame

Prepared by Prof. Dr. Syeda Husna


15. frame.getContentPane().setLayout(new FlowLayout());
16. JTextArea textArea = new JTextArea(20, 20);
17. JScrollPane scrollableTextArea = new JScrollPane(textArea);
18. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AL
WAYS);
19. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLB
AR_ALWAYS);
20. frame.getContentPane().add(scrollableTextArea);
21. }
22. public static void main(String[] args) {
23. javax.swing.SwingUtilities.invokeLater(new Runnable() {
24. public void run() {
25. createAndShowGUI();
26. }
27. });
28. }
29. }

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.

JTree class declaration

Let's see the declaration for javax.swing.JTree class.

Prepared by Prof. Dr. Syeda Husna


1. public class JTree extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as the child of a
value) new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the
root) root node.

Java JTree Example


1. import javax.swing.*;
2. import javax.swing.tree.DefaultMutableTreeNode;
3. public class TreeExample {
4. JFrame f;
5. TreeExample(){
6. f=new JFrame();
7. DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
8. DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
9. DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
10. style.add(color);
11. style.add(font);
12. DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
13. DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
14. DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
15. DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
16. color.add(red); color.add(blue); color.add(black); color.add(green);
17. JTree jt=new JTree(style);
18. f.add(jt);
19. f.setSize(200,200);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {

Prepared by Prof. Dr. Syeda Husna


23. new TreeExample();
24. }}

Output:

JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration

Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example


1. import javax.swing.*;
2. public class TableExample {
3. JFrame f;
4. TableExample(){
5. f=new JFrame();
6. String data[][]={ {"101","Amit","670000"},
7. {"102","Jai","780000"},

Prepared by Prof. Dr. Syeda Husna


8. {"101","Sachin","700000"}};
9. String column[]={"ID","NAME","SALARY"};
10. JTable jt=new JTable(data,column);
11. jt.setBounds(30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. f.add(sp);
14. f.setSize(300,400);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }

Output:

Prepared by Prof. Dr. Syeda Husna

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy