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

OOP thr Java-UNIT 5

Unit V covers the concepts of applets and Swing in Java, detailing the differences between applets and applications, the applet life cycle, and how to create applets. It explains the advantages of applets, the process of passing parameters, and introduces Swing as a more sophisticated GUI toolkit compared to AWT. The unit also highlights the limitations of AWT and provides examples of creating GUI applications using both AWT and Swing components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

OOP thr Java-UNIT 5

Unit V covers the concepts of applets and Swing in Java, detailing the differences between applets and applications, the applet life cycle, and how to create applets. It explains the advantages of applets, the process of passing parameters, and introduces Swing as a more sophisticated GUI toolkit compared to AWT. The unit also highlights the limitations of AWT and provides examples of creating GUI applications using both AWT and Swing components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

OOP through Java 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


Applets are small applications that are accessed on an Internet server, transported
over the Internet, automatically installed, and run as part of a web document.

This applet begins with two import statements.


 The first imports the Abstract Window Toolkit (AWT) classes. Applets
interact with the user (either directly or indirectly) through the AWT, not
through the console-based I/O classes. The AWT contains support for a window-
based, graphical user interface
 The second import statement imports the applet package, which contains the
class Applet. Every applet that you create must be a subclass of Applet

The AWT contains window-based, graphical user interface. The paint( ) method has
one parameter of type Graphics. Inside paint( ) is a call to drawString( ), which is a
member of the Graphics class. This method outputs a string beginning at the specified
X, Y location.

It has the following general form:


 void drawString(String message, int x, int y)

An applet viewer executes your applet in a window. To execute an applet in a web


browser, you need to write a short HTML text file that contains a tag that loads the
applet. Applets do not need a main( ) method. Applets must be run under an applet
viewer or a Java-compatible browser. User I/O is not accomplished with Java’s stream
I/O classes. Instead, applets use the interface provided by the AWT or Swing.

Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms, including Linux,
Windows, Mac OS etc.

Setting the path


After downloading the Java software any version double click the application, then
click YES, next click next button etc finally installed then close

Now open cmd prompt set the path like


C:\Users\Admin>echo %PATH%

P.Ramesh, Assistant Professor, AIMLDept, TKREC 1


OOP through Java UNIT-5

C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program


Files\Java\jdk-16\bin;

C:\Users\Admin>set PATH=%PATH%;C:\Program Files\Java\jdk-1.8\bin

C:\Users\Admin>JAVAC
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info

Now open System


Go to MyComputer properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable value
-> ok -> ok -> ok

Like PATH= C:\Program Files\Java\jdk-1.8\bin;.; then click ok.

Differences between applets and applications

Java Application: 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: An applet is a Java program that can be embedded into a web page. It
runs inside the web browser and works at 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 web site more dynamic and entertaining.

Java Application Java Applet


Applications are just like a Java Applets are small Java programs that are
programs that can be execute designed to be included with the HTML
independently without using the web web document. They require a Java-
browser. enabled web browser for execution.
Application program requires a main Applet does not require a main function
function for its execution. for its execution.
Java application programs have the full
access to the local file system and Applets don’t have local disk and
network. network access.
Applets can only access the browser
Applications can access all kinds of specific services. They don’t have access
resources available on the system. to the local system.
Applications can executes the programs Applets cannot execute programs from
from the local system. the local machine.
An application program is needed to An applet program is needed to perform
perform some task directly for the user. small tasks or the part of it.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 2


OOP through Java UNIT-5

Lifecycle of Java Applet

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.

Types of applets

There are two varieties of applets


 The first are those based directly on the Applet class. These applets use the
Abstract Window Toolkit (AWT) to provide the graphic user interface (or use no
GUI at all). This style of applet has been available since Java was first created.
 The second type of applets are those based on the Swing class JApplet. Swing
applets use the Swing classes to provide the GUI. Swing offers a richer and often
easier-to-use user interface than does the AWT. Thus, Swing-based applets are
now the most popular. JApplet inherits Applet, all the features of Applet are also
available in JApplet.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 3


OOP through Java UNIT-5

Creating applets
For creating any applet java.applet.Applet class must be inherited. It provides life
cycle methods of applet.
 public void init(): is used to initialized the Applet. It is invoked only once.
 public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
 public void paint(): ) is called each time your applet’s output must be redrawn.
It is also called when the applet begins execution.
 public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked only once.

Syntax of entire Applet Life Cycle in Java

class TestAppletLifeCycle extends Applet


{
public void init() {
// initialized objects
}
public void start() {
// code to start the applet
}
public void paint(Graphics graphics) {
// draw the shapes
}
public void stop() {
// code to stop the applet
}
public void destroy() {
// code to destroy the applet
}
}

// Sample Applet Example File: First.java

import java.awt.*;
import java.applet.*;

public class SimpleApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 50, 50);
}
}

// html file: Applet.html

<html>

P.Ramesh, Assistant Professor, AIMLDept, TKREC 4


OOP through Java UNIT-5

<body>
Here is the output of my program:
<applet code="SimpleApplet.class" width="250" height="200"></applet>
</body>
</html>

OUTPUT:
D:\Java>javac SimpleApplet.java
D:\Java>appletviewer Applet.html

// Java program to run the applet using the applet viewer

import java.awt.*;
import java.applet.*;
public class SimpleExample extends Applet
{
String msg="";
public void init()
{
msg="Hello Java ";
}
public void start()
{
msg=msg+" Welcome to Applet";
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
Font f=new Font("verdana", Font.BOLD, 12);
g.setFont(f);
g.drawString(msg,20,30);
}
}
/*
<applet code="SimpleExample" width=250 height=200>

P.Ramesh, Assistant Professor, AIMLDept, TKREC 5


OOP through Java UNIT-5

</applet>
*/
OUTPUT:
D:\Java>javac SimpleExample.java
D:\Java>appletviewer SimpleExample.java

Passing parameters to applets


The APPLET tag allows you to pass parameters to your applet. To retrieve a parameter,
use the getParameter( ) method. It returns the value of the specified parameter in the
form of a String object. Thus, for numeric and boolean values, you will need to convert
their string representations into their internal formats. Here is an example that
demonstrates passing parameters:

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 passingParameter to the 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);
}
}

// Example of passingParameter to the Applet

P.Ramesh, Assistant Professor, AIMLDept, TKREC 6


OOP through Java UNIT-5

<html>
<body>
<applet code="UseParam.class" width="300" height="100">
<param name="msg" value="Welcome to Applet in Java ">
</applet>
</body>
</html>

OUTPUT:
D:\Java> javac UseParam.java
D:\Java> appletviewer UseParam.html

Swing – Introduction
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 programs 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 GUI programming
components like button, textbox, etc. from the library and do not have to create the
components from scratch.

The components of Swing are platform-independent, i.e., swing doesn't depend on


the operating system to show the components. Also, the Swing's components are
lightweight.

Java Swing class Hierarchy Diagram


All components in Java Swing are JComponent which can be added to container classes.
Container classes are classes that can have other components on it. So for creating a
Java GUI, we need at least one container object. There are 3 types of Java Swing
containers.
 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.
 Frame: It is a fully functioning window with its title and icons.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 7


OOP through Java UNIT-5

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

Swing class Hierarchy Diagram

GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for
Java applications. It is mainly made of graphical components like buttons, labels,
windows, etc. through which the user can interact with an application. GUI plays an
important role to build easy interfaces for Java applications.

// GUI with Java Swing example

import javax.swing.*;
class Gui
{
public static void main(String args[])
{
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}

OUTPUT:
D:\Java>javac Gui.java
D:\Java>java Gui

P.Ramesh, Assistant Professor, AIMLDept, TKREC 8


OOP through Java UNIT-5

Creating Java Swing Example


A simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

Import javax.swing.*;
public class SwingDemo
{
public static void main(String[] args)
{
//creating instance of JFrame
JFrame f=new JFrame("Swing Creation");

//creating instance of JButton


JButton b=new JButton("Hello !");

//x axis, y axis, width, height


b.setBounds(130,100,100, 40);

//adding button in JFrame


f.add(b);

//300 width and 400 height


f.setSize(300,400);

//using no layout managers


f.setLayout(null);

//making the frame visible


f.setVisible(true);
}
}
OUTPUT:
D:\Java>javac SwingDemo.java
D:\Java>java SwingDemo

P.Ramesh, Assistant Professor, AIMLDept, TKREC 9


OOP through Java UNIT-5

Limitations of AWT
 AWT has limited GUI components; components like table, tree, progress bar
cannot be supported by AWT. 
 Although AWT is thread-safe, it slows down the running speed of GUI.
 Generally speaking, AWT GUI is inaccessible because it does not provide APIs for
AWT programmers to specify accessible information. 
 Because of variations between operating systems, a component might look, or
even act, differently on different platforms. This variability threatened java’s
philosophy: write once, run anywhere. 
 The look and feel of each component was fixed and could not be changed.
 The use of heavyweight components caused some frustrating restrictions. Due to
these limitations Swing came and was integrated to java. 

Difference between AWT and Swing

Java AWT Java Swing


AWT components are platform- Java swing components are
dependent. platform independent.
AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
AWT provides less components than Swing provides more powerful
Swing. Components such as tables, lists, scroll
panes, color chooser, tabbed pane etc
AWT doesn't follows MVC Swing follows MVC.

AWT components, containers

P.Ramesh, Assistant Professor, AIMLDept, TKREC 10


OOP through Java UNIT-5

The hierarchy of the AWT Container classes is as follows:

// AWT Example

importjava.awt.*;
public class AwtDemo
{
AwtDemo()
{
Frame f = new Frame();
Button btn=new Button("Hello World");
btn.setBounds(80, 80, 100, 50);
//adding a new Button.
f.add(btn);
//setting size.
f.setSize(300, 250);
//setting title.
f.setTitle("Java Programming");

//set default layout for frame.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 11


OOP through Java UNIT-5

f.setLayout(null);
//set frame visibility true.
f.setVisible(true);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
//creating a frame.
AwtDemo awt = new AwtDemo();
}
}
OUTPUT:
D:\TKREC\Java>javac AwtDemo.java
D:\TKREC\Java>java AwtDemo

// AWT Components Example

import java.awt.*;
public class AwtApplication extends Frame
{
AwtApplication()
{
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);

Label lastName = new Label("Last Name");


lastName.setBounds(20, 80, 80, 20);

Label dob = new Label("Date of Birth");


dob.setBounds(20, 110, 80, 20);

TextField firstNameTF = new TextField();


firstNameTF.setBounds(120, 50, 100, 20);

TextField lastNameTF = new TextField();


lastNameTF.setBounds(120, 80, 100, 20);

P.Ramesh, Assistant Professor, AIMLDept, TKREC 12


OOP through Java UNIT-5

TextField dobTF = new TextField();


dobTF.setBounds(120, 110, 100, 20);

Button sbmt = new Button("Submit");


sbmt.setBounds(20, 160, 100, 30);

Button reset = new Button("Reset");


reset.setBounds(120,160,100,30);

add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
AwtApplication awt = new AwtApplication();
}
}
OUTPUT:
D:\Java>javac AwtApplication.java
D:\Java>java AwtApplication

MVC architecture
Swing API architecture follows loosely based MVC architecture in the following manner.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 13


OOP through Java UNIT-5

 Model represents component's data.


 View represents visual representation of the component's data.
 Controller takes the input from the user on the view and reflects the changes in
Component's data.

Swing component has Model as a separate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.

Exploring swing- JApplet


Swing-based applets are similar to AWT-based applets, but with an important
difference: A Swing applet extends JApplet rather than Applet. JApplet is derived
from Applet. Thus, JApplet includes all of the functionality found in Applet and adds
support for Swing.

JApplet is a top-level Swing container, which means that it is not derived


from JComponent. Because JApplet is a top-level container, it includes the various
panes described earlier. Swing applets use the same four life-cycle methods i.e. init(
), start( ), stop( ), and destroy( ).

Now we can use JApplet that can have all the controls of swing. The JApplet class
extends the Applet class

// A simple Swing-based applet File: SwingApplet.java

import javax.swing.*;
P.Ramesh, Assistant Professor, AIMLDept, TKREC 14
OOP through Java UNIT-5

import java.awt.*;
import java.awt.event.*;

/*
<applet code="SwingApplet" width=220 height=110>
</applet>
*/
public class SwingApplet extends JApplet
{
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;

// Initialize the applet.


public void init()
{
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can’t create because of "+ exc);
}
}
//This applet does not need to override start(), stop(), or destroy().Set up and initialize
the GUI.
private void makeGUI()
{
//Set the applet to use flow layout.
setLayout(new FlowLayout());

//Make two buttons.


jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");

//Add action listener for Alpha.


jbtnAlpha.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent le)
{
jlab.setText("Alpha was pressed.");
}
});

//Add action listener for Beta.


jbtnBeta.addActionListener(new ActionListener()
{

P.Ramesh, Assistant Professor, AIMLDept, TKREC 15


OOP through Java UNIT-5

public void actionPerformed(ActionEvent le)


{
jlab.setText("Beta was pressed.");
}
});

//Add the buttons to the content pane.


add(jbtnAlpha);
add(jbtnBeta);

//Create a text-based label.


jlab = new JLabel("Press a button.");

// Add the label to the content pane.


add(jlab);
}
}

OUTPUT:
D:\TKREC\Java> javac SwingApplet.java
D:\TKREC\Java> appletviewer SwingApplet.java

JFrame and JComponent


// Paint lines to a panel.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/* This class extends JPanel. It overrides the paintComponent() method so that random
lines are plotted in the panel.*/

class PaintPanel extends JPanel


{
// holds the panel’s insets

P.Ramesh, Assistant Professor, AIMLDept, TKREC 16


OOP through Java UNIT-5

Insets ins;
// used to generate random numbers
Random rand;

// Construct a panel.
PaintPanel()
{
// Put a border around the panel.
setBorder(BorderFactory.createLineBorder(Color.blue, 5));
rand = new Random();
}
// Override the paintComponent() method.
protected void paintComponent(Graphics g)
{
// Always call the superclass method first.
super.paintComponent(g);
int x, y, x2, y2;
// Get the height and width of the component.
int height = getHeight();
int width = getWidth();

// Get the insets.


ins = getInsets();
// Draw ten lines whose endpoints are randomly generated.
for(int i=0; i < 4; i++)
{
// Obtain random coordinates that define the endpoints of each line.
x = rand.nextInt(width-ins.left);
y = rand.nextInt(height-ins.bottom);
x2 = rand.nextInt(width-ins.left);
y2 = rand.nextInt(height-ins.bottom);
g.drawLine(x, y, x2, y2);
}
}
}
// Demonstrate painting directly onto a panel.
public class PaintDemo
{
JLabel jlab;
PaintPanel pp;
PaintDemo()
{
// Create a new JFrame container.
JFrame jfrm = new JFrame("Paint Demo");
jfrm.setSize(300, 200);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the panel that will be painted.


pp = new PaintPanel();

P.Ramesh, Assistant Professor, AIMLDept, TKREC 17


OOP through Java UNIT-5

jfrm.add(pp);
jfrm.setVisible(true);
}
public static void main(String args[])
{
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new PaintDemo();
}
});
}
}
OUTPUT:
D:\Java>javac PaintDemo.java
D:\TKREC\Java> java PaintDemo

Icons and Labels, text fields

Here is the ImageIcon constructor used by the example in this section:


 ImageIcon(String filename): It obtains the image in the file named filename.

The icon and text associated with the label can be obtained by the following methods:
 Icon getIcon( )
 String getText( )

The icon and text associated with a label can be set by these methods:
 void setIcon(Icon icon)
 void setText(String str)

JLabel defines several constructors.


 JLabel(Icon icon)
 JLabel(String str)
 JLabel(String str, Icon icon, int align)

// Demonstrate JLabel and Image Icon.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 18


OOP through Java UNIT-5

import java.awt.*;
import javax.swing.*;

/*
<applet code="JLabelDemo" width=250 height=200>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Create an icon.
ImageIcon ii = new ImageIcon(“Hourglass.gif");

// Create a label.
JLabel jl = new JLabel("Hourglass", ii, JLabel.CENTER);

// Add the label to the content pane.


add(jl);
}
}

OUTPUT:
D:\Java>javac JLabelDemo.java
D:\Java> appletviewer JLabelDemo.java

P.Ramesh, Assistant Professor, AIMLDept, TKREC 19


OOP through Java UNIT-5

JText Field
Three of JTextField’s constructors are shown here:
 JTextField(int cols)
 JTextField(String str, int cols)
 JTextField(String str)

// Demonstrate JTextField.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="JTextFieldDemo" width=300 height=100>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}

private void makeGUI() {

// Change to flow layout.


setLayout(new FlowLayout());

// Add text field to content pane.


jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{

// Show text when user presses ENTER.


showStatus(jtf.getText());
}
});

P.Ramesh, Assistant Professor, AIMLDept, TKREC 20


OOP through Java UNIT-5

}
}

OUTPUT:
D:\TKREC\Java>javac JTextFieldDemo.java
D:\TKREC\Java> appletviewer JTextFieldDemo.java

Buttons – The JButton class, Check boxes, Radio buttons, Combo


boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.

The JButton class


The JButton class provides the functionality of a push button. JButton allows an icon, a
string, or both to be associated with the push button. Three of its constructors are
shown here:
 JButton(Icon icon)
 JButton(String str)
 JButton(String str, Icon icon)

Here, str and icon are the string and icon used for the button.

When the button is pressed, an ActionEvent is generated. Using the ActionEvent object
passed to the actionPerformed( ) method of the registered ActionListener, you can
obtain the action command string associated with the button.You can obtain the action
command by calling getActionCommand( ) on the event object. It is declared like this:
 String getActionCommand( )

// demonstrate an icon-based JButton.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="JButtonDemo" width=200 height=300>
</applet>
*/

public class JButtonDemo extends JApplet implements ActionListener


{
P.Ramesh, Assistant Professor, AIMLDept, TKREC 21
OOP through Java UNIT-5

JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Change to flow layout.
setLayout(new FlowLayout());

// Add buttons to content pane.


ImageIcon hourglass = new ImageIcon("hourglass.gif");
JButton jb = new JButton(hourglass);
jb.setActionCommand("Hourglass");
jb.addActionListener(this);
add(jb);

ImageIcon analog = new ImageIcon("analog.gif");


jb = new JButton(analog);
jb.setActionCommand("Analog Clock");
jb.addActionListener(this);
add(jb);

ImageIcon digital = new ImageIcon("digital.gif");


jb = new JButton(digital);
jb.setActionCommand("Digital Clock");
jb.addActionListener(this);
add(jb);

ImageIcon stopwatch = new ImageIcon("stopwatch.gif");


jb = new JButton(stopwatch);
jb.setActionCommand("Stopwatch");
jb.addActionListener(this);
add(jb);

// Create and add the label to content pane.


jlab = new JLabel("Choose a Timepiece");
add(jlab);
}

// Handle button events.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 22


OOP through Java UNIT-5

public void actionPerformed(ActionEvent ae)


{
jlab.setText("You selected " + ae.getActionCommand());
}
}

OUTPUT:
D:\Java>javac JButtonDemo.java
D:\Java>appletviewer JButtonDemo.java

JCheck Boxes
The JCheckBox class provides the functionality of a check box. Its immediate superclass
is JToggleButton, which provides support for two-state buttons, as just described.

JCheckBox defines several constructors. The one used here is


 JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors let
you specify the initial selection state of the button and specify an icon.

The JCheckBox that generated the event by calling getItem( ) on the ItemEvent passed
to the itemStateChanged( ) method defined by ItemListener. The easiest way to
determine the selected state of a check box is to call isSelected( ) on the JCheckBox
instance.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 23


OOP through Java UNIT-5

// Demonstrate JCheckbox.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="JCheckBoxDemo" width=250 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet implements ItemListener
{
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Change to flow layout.
setLayout(new FlowLayout());

// Add check boxes to the content pane.


JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
add(cb);

cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);

cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);

cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);

P.Ramesh, Assistant Professor, AIMLDept, TKREC 24


OOP through Java UNIT-5

// Create the label and add it to the content pane.


jlab = new JLabel("Select languages");
add(jlab);
}
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
}

OUTPUT:
D:\TKREC\Java>javac JCheckBoxDemo.java
D:\TKREC\Java appletviewer JCheckBoxDemo.java

JRadio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can
be selected at any one time. They are supported by the JRadioButton class, which
extends JToggleButton.

JRadioButton provides several constructors. The one used in the example is shown
here:
 JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial
selection state of the button and specify an icon.

A button group is created by the ButtonGroup class. Its default constructor is invoked
for this purpose. Elements are then added to the button group via the following method:
 void add(AbstractButton ab)

P.Ramesh, Assistant Professor, AIMLDept, TKREC 25


OOP through Java UNIT-5

Here, ab is a reference to the button to be added to the group.

A JRadioButton generates action events, item events, and change events each time the
button selection changes. Most often, it is the action event that is handled, which means
that you will normally implement the ActionListener interface.

// Demonstrate JRadioButton

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="JRadioButtonDemo" width=280 height=50>
</applet>
*/

public class JRadioButtonDemo extends JApplet implements ActionListener


{
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception ex) {
System.out.println("Can't create because of " + ex);
}
}
private void makeGUI()
{
// Change to flow layout.
setLayout(new FlowLayout());

// Create radio buttons and add them to content pane.


JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);

JRadioButton b2 = new JRadioButton("B");


b2.addActionListener(this);
add(b2);

JRadioButton b3 = new JRadioButton("C");


b3.addActionListener(this);
add(b3);

P.Ramesh, Assistant Professor, AIMLDept, TKREC 26


OOP through Java UNIT-5

// Define a button group.


ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);

// Create a label and add it to the content pane.


jlab = new JLabel("Select One");
add(jlab);
}

// Handle button selection.


public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}

OUTPUT:
D:\TKREC\Java>javac JRadioButtonDemo.java
D:\TKREC\Java>appletviewer JRadioButtonDemo.java

JCombo Box
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but it will also
display a dropdown list that allows a user to select a different entry. You can also create
a combo box that lets the user enter a selection into the text field.
The JComboBox constructor used by the example is shown here:
JComboBox(E[ ] items) Here, items is an array that initializes the combo box. Other
constructors are available
JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries can
be changed) use the MutableComboBoxModel.

JComboBox generates an action event when the user selects an item from the list.
JComboBox also generates an item event when the state of selection changes, which
occurs when an item is selected or deselected.

One way to obtain the item selected in the list is to call getSelectedItem( ) on the combo
box. It is shown here:
Object getSelectedItem()

// Demonstrate JComboBox

P.Ramesh, Assistant Professor, AIMLDept, TKREC 27


OOP through Java UNIT-5

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
<applet code="JComboBoxDemo" width=300 height=250>
</applet>
*/

public class JComboBoxDemo extends JApplet


{
JLabel jlab;
ImageIcon hourglass, analog, digital, stopwatch, analogwatch1;
JComboBox<String> jcb;
String timepieces[] = { "Hoursglass","Analog", "Digital", "Stopwatch", "Analogwatch1" };
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}

private void makeGUI()


{
setLayout(new FlowLayout()); // Change to flow layout.

// Instantiate a combo box and add it to the content pane.


jcb = new JComboBox<String>(timepieces);
add(jcb);

// Handle selections.
jcb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".png"));
}
});

// Create a label and add it to the content pane.


jlab = new JLabel(new ImageIcon("hourglass.jpg"));

P.Ramesh, Assistant Professor, AIMLDept, TKREC 28


OOP through Java UNIT-5

add(jlab);
}
}

OUTPUT:
D:\TKREC\Java>javac JComboBoxDemo.java
D:\TKREC\Java> appletviewer JComboBoxDemo.java

JTabbed Pane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking
them with tabs. Selecting a tab causes the component associated with that tab to come
to the forefront. Tabbed panes are very common in the modern GUI.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 29


OOP through Java UNIT-5

JTabbedPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane.

Here is one of its forms:


 void addTab(String name, Component comp)
Here, name is the name for the tab, and comp is the component that should be added to
the tab. Often, the component added to a tab is a JPanel that contains a group of related
components.

The general procedure to use a tabbed pane is outlined here:


 Create an instance of JTabbedPane.
 Add each tab by calling addTab( ).
 Add the tabbed pane to the content pane.

// Demonstrate JTabbedPane.

import javax.swing.*;

/*
<applet code="JTabbedPaneDemo" width=300 height=250>
</applet>
*/

public class JTabbedPaneDemo extends JApplet


{
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}

// Make the panels that will be added to the tabbed pane.


class CitiesPanel extends JPanel

P.Ramesh, Assistant Professor, AIMLDept, TKREC 30


OOP through Java UNIT-5

{
CitiesPanel()
{
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}

class ColorsPanel extends JPanel


{
ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
FlavorsPanel()
{
JComboBox<String> jcb = new JComboBox<String>();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}

OUTPUT:
D:\TKREC\Java>javac JTabbedPaneDemo.java
D:\TKREC\Java>appletviewer JTabbedPaneDemo.java

P.Ramesh, Assistant Professor, AIMLDept, TKREC 31


OOP through Java UNIT-5

JScroll Pane
JScroll Pane is a lightweight container that automatically handles the scrolling of
another component. The component being scrolled can be either an individual
component, such as a table, or a group of components contained within another
lightweight container, such as a JPanel.

The viewable area of a scroll pane is called the viewport. It is a window in which the
component being scrolled is displayed. JScrollPane defines several constructors. The
one used in this chapter is shown here:
 JScrollPane(Component comp)

Here are the steps to follow to use a scroll pane:


 Create the component to be scrolled.
 Create an instance of JScrollPane, passing to it the object to scroll.
 Add the scroll pane to the content pane.

// Demonstrate JScrollPane.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 32


OOP through Java UNIT-5

import java.awt.*;
import javax.swing.*;

/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/

public class JScrollPaneDemo extends JApplet


{
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
// Add 100 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(10, 10));
int b = 0;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}

// Create the scroll pane.


JScrollPane jsp = new JScrollPane(jp);

/* Add the scroll pane to the content pane.Because the default border layout is used,
the scroll pane will be added to the center
*/
add(jsp, BorderLayout.CENTER);
}
}

OUTPUT:
D:\TKREC\Java>javac JScrollPaneDemo.java
D:\TKREC\Java> appletviewer JScrollPaneDemo.java

P.Ramesh, Assistant Professor, AIMLDept, TKREC 33


OOP through Java UNIT-5

Trees
A tree is a component that presents a hierarchical view of data. The user has the ability
to expand or collapse individual subtrees in this display. Trees are implemented in
Swing by the JTree class.

A sampling of its constructors is shown here:


 JTree(Object obj[ ])
 JTree(Vector<?> v)
 JTree(TreeNode tn)
To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can
be used. Its signature is shown here:
 void add(MutableTreeNode child)

Here are the steps to follow to use a tree:


 Create an instance of JTree.
 Create a JScrollPane and specify the tree as the object to be scrolled.
 Add the tree to the scroll pane.
 Add the scroll pane to the content pane.

// Demonstrate JTree.

import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
<applet code="JTreeDemo" width=300 height=250>
</applet>
*/

P.Ramesh, Assistant Professor, AIMLDept, TKREC 34


OOP through Java UNIT-5

public class JTreeDemo extends JApplet {


JTree tree;
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
});
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

// Create subtree of "A".


DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);

// Create subtree of "B".


DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);

// Create the tree.


tree = new JTree(top);

// Add the tree to a scroll pane.


JScrollPane jsp = new JScrollPane(tree);

// Add the scroll pane to the content pane.


add(jsp);

// Add the label to the content pane.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 35


OOP through Java UNIT-5

jlab = new JLabel();


add(jlab, BorderLayout.SOUTH);

// Handle tree selection events.


tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
jlab.setText("Selection is " + tse.getPath());
}
});
}
}
OUTPUT:
D:\Java>javac JTreeDemo.java
D:\Java>appletviewer JTreeDemo.java

JTable
JTable is a component that displays rows and columns of data. JTable does not provide
any scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a
JScrollPane.

JTable supplies several constructors. The one used here is


 JTable(Object data[ ][ ], Object colHeads[ ])

Here are the steps required to set up a simple JTable that can be used to display
data:
 Create an instance of JTable.
 Create a JScrollPane object, specifying the table as the object to scroll.
 Add the table to the scroll pane.
 Add the scroll pane to the content pane.

// Demonstrate JTable.

P.Ramesh, Assistant Professor, AIMLDept, TKREC 36


OOP through Java UNIT-5

import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);
}
}
OUTPUT:
D:\Java>javac JTableDemo.java

P.Ramesh, Assistant Professor, AIMLDept, TKREC 37


OOP through Java UNIT-5

D:\Java>appletviewer JTableDemo.java

P.Ramesh, Assistant Professor, AIMLDept, TKREC 38

You might also like