Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit V

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

UNIT-V

Applets
Applet :
Applets are basically small java programs which can be easily transported
over the network from one computer to other. They are used in internet
applications, where these applets , embedded in an html page can be downloaded
from the server and run on the client, so as to do a specific kind of job.

These applets have the capability of displaying graphics, playing sound,


creating animation, and performing other jobs that can be done by simple
application programs.

To execute these applets on the client, the client must have either a

1. java enabled browser or web browser


2. appletviewer

All applets are sub classes of java.applet. Applet class.

In general, execution of an applet does not begin at main() method.Output of an


applet window is not performed by System.out.println() rather it is handled with
various AWT methods, such as drawstring().

Applet Types:

Applets are of two types.

1. conventional applets : They are directly evolved from Applet class. These
applets use Abstract Window ToolKit(AWT) to get GUI features.
2. Another type of applets are those which are based on Swing class for
drawing and display of graphics, JApplet.

Advantage of Applets

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 platforms,
including Linux, Windows, Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to execute applet.

Differences between Applet and Application

BASIS FOR
APPLET APPLICATION
COMPARISON

Basic It is small program uses another An application is the programs executed


application program for its on the computer independently.
execution.

main() method Do not use the main method Uses the main method for execution

Execution Cannot run independently Can run alone but require JRE.
require API's (Ex. Web API).

Installation Prior installation is not needed Requires prior explicit installation on the
local computer.

Read and write The files cannot be read and Applications are capable of performing
operation write on the local computer those operations to the files on the local
through applet. computer.

Communication with Cannot communicate with other Communication with other servers is
other servers servers. probably possible.

Restrictions Applets cannot access files Can access any data or file available on
BASIS FOR
APPLET APPLICATION
COMPARISON

residing on the local computer. the system.

Security Requires security for the system No security concerns are there.
as they are untrusted.

Applet class:
java.applet.Applet is the superclass of all the applets. Thus all the applets,
directly or indirectly use the methods of Applet belonging java.applet package.This
class provides all the necessary methods for starting ,stoping and manipulating
applets.

Hierarchy of Applet class

java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Panel

java.applet.Applet
Applet class Methods

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.
5. URL getDocumentBase(): Gets the URL of the document in which this applet is
embedded.
6. void resize(int width,int height):Resizes the applet according to the parameters ,
width and height.
7. String getAppletInfo():Returns string describing applet

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.

Applet structure or skeleton:

Apart from using the services of Applet class, an applet also uses the
services of Graphics class of the java.awt package. The applet class has
methods such as init(), start(),stop() and destroy() which are responsible for the
birth and behavior of an applet.

java Runtime systems does not call the main() method to start the execution
of an applet like in an application program rather it just loads the methods of
applet class which are responsible for starting, running , stopping and
manipulating an applet.

As applet output text,graphics, sounds etc; the output operations for an


applet requires the methods contained in the Graphics class, that is why its
Graphics object is passed as argument to paint().
import java.awt.*;

import java.applet.*;

public class MyApplet extends Applet

public void init()

//initialization

public void start()

//start or resume execution

public void paint(Graphics g)

//redisplay contents of window

public void stop()

{
//suspends execution

public void destroy()

//perform shutdown activities

Applet Life cycle

Different states that an applet experiences between its objects creation and
object removal is known as Applet Life Cycle.

Applet life cycle consists of 5 methods, representing 4 states.


1.init()
2. start()
3.paint()
4.stop()
5.destroy()

1.public void init() :

this method is called at the time of starting the execution. This is called only
once in the life cycle. This method initializes the Applet and it helps to initialize
variables and instantiate the objects and load the GUI of the applet. This is
invoked when the page containing the applet is loaded and places the applet in
new born state.
Its general form is:
public void init()
{
---
---
}
2.start() method:
The start() method executes immediately after the init() method. It starts the
execution of Applet. In this state the applet becomes active. It also executes
whenever the applet is restored, maximized or moving from one tab to another
tab in the browser.
public void start()
{

}
3.stop() method:
The stop() method stops the execution of the applet. It is invoked when the
Applet or the browser is minimized. The applet frequently comes to this state in
its life cycle and can go back to its active state.

public void stop()


{
}

4.paint() method:
This method helps to create Applet’s GUI such as a colored background and
writing. The paint() method executes after the execution of start() method and
whenever the applet or browser is resized.

public void paint(Graphics g)


{
}

5.destroy() method:
this method destroys the Applet and is also invoked only once when the
active browser page containing the applet is closed.
public void destroy()
{
}
when an applet is closed ,the method execution sequence is stop(), destroy()

creating and executing Applet:


1.create an html file with <Applet> tag
2. create a java code for applet
3. compile code and get class file
4. Run the html file (using web browser or appletviewer)
1.create an html file <Applet> tag: Applets are embedded in html document
using
<Applet code=classfile name width= height= align= >

<html>
<body>
<Applet code=”MyApplet.class” width=200 height=200>
</Applet>
</html>
2. create a java code for applet
MyApplet.java
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“MIC College”,150,150);
}
}

3. compile code and get class file


d:\> javac MyApplet.java
4. Run the html file
d:\>appletviewer MyApplet.html

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw
line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font
to the specified font.
Ex2: Write java program to draw different shapes

import java.applet.*;
import java.awt.*;
public class MyApplet1 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(30,200,300,10);
g.drawOval(50,50,100,100);
g.drawRect(100,100,100,100);
}
}

save : MyApplet1.java

create a html file

<html>
<body>
<Applet code="MyApplet1.class" height=300

width=300>
</Applet>
</body>
</html>

save : MyApplet1.html
Run : appletviewer MyApplet1.html
Ex3: Java program to create different shapes and fill colors using applet

import java.applet.*;
import java.awt.*;
public class MyApplet2 extends Applet
{
public void paint(Graphics g)
{
g.drawLine(30,200,300,10);
g.setColor(Color.blue);
g.drawOval(50,50,100,100);
g.setColor(Color.red);
g.drawRect(100,100,100,100);
g.fillRect(60,10,30,50);
}
}
save : MyApplet2.java
compile : javac MyApplet.java

create a html file


<html>
<body>
<Applet code=MyApplet2.class height=200 width=200>
</Applet>
</body>
</html>
save : MyApplet2.html
run : appletviewer MyApplet2.html
Types of Applets in 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

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.

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.

passing parameters 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 java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("message");
g.drawString(str,50, 50);
}
}
Java Swing :

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.

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

Differences between java 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 look


and feel. and feel.

4) AWT provides less components than Swing provides more powerful


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

MVC Architecture

MVC is an architectural pattern consisting of three parts: Model, View, Controller. Model: Handles data
logic. View: It displays the information from the model to the user. Controller: It controls the data flow into
a model object and updates the view whenever data changes

The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.
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 height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the


component.

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.

import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
/*<Applet code=EventJApplet.class height=500 width=500>
</Applet>
*/
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){

tf=new JTextField();
tf.setBounds(30,40,150,20);

b=new JButton("Click");
b.setBounds(80,150,70,40);

add(b);add(tf);
b.addActionListener(this);

setLayout(null);
}

public void actionPerformed(ActionEvent e){


tf.setText("Welcome to swings ");
}
}
JPanel
The JPanel is a simplest container class. It provides space in which an application
can attach any other component. It inherits the JComponents class.

It doesn't have title bar.

Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer


and a flow layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and


isDoubleBuffered) the specified buffering strategy.

JPanel(LayoutManager It is used to create a new JPanel with the specified


layout) layout manager.

JPanel Example
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PanelExample implements ActionListener{
JLabel l;
JButton b1,b2;
PanelExample()
{

JFrame f= new JFrame("Panel Example");


JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
b1=new JButton("Yellow");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);

b2=new JButton("Green");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);

l=new JLabel();
l.setBounds(50,280,80,30);
l.setForeground(Color.orange);

panel.add(b1);
panel.add(b2);
panel.add(l);

f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
l.setText(s+" button clicked");
}
public static void main(String args[])
{
new PanelExample();
}
}

Java Swing Examples


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.

Ex : java program to create a frame using swings

import javax.swing.*;
public class Simple
{
JFrame f;
Simple()
{
f=new JFrame();//creating instance of JFrame

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


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

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}

public static void main(String[] args)


{
new Simple();
}
}

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.

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.

Ex :JButton example

import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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.

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

t returns the text string that a label


String getText()
displays.

void setText(String text) It defines the single line of text this


component will display.

It sets the alignment of the label's contents


void setHorizontalAlignment(int alignment)
along the X axis.

It returns the graphic image that the label


Icon getIcon()
displays.

It returns the alignment of the label's


int getHorizontalAlignment()
contents along the X axis.

Ex :

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("MIC COLLEGE.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("KANCHIKACHERLA");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField:

The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the


specified text.

JTextField(String text, int columns) Creates a new TextField initialized with the
specified text and columns.

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


number of columns.

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 It is used to remove the specified action listener


removeActionListener(ActionListener l) so that it no longer receives action events from
this textfield.

Ex :

import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to mic");
t1.setBounds(50,100, 200,30);
t2=new JTextField("java swings”);
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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.

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button


with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies
selected) whether or not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken


from the Action supplied.

Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext


getAccessibleContext() associated with this JCheckBox.

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


JCheckBox.
Ex:

import javax.swing.*;

public class SCheckBoxExample

SCheckBoxExample(){

JFrame f= new JFrame("CheckBox Example");

JCheckBox checkBox1 = new JCheckBox("C++");

checkBox1.setBounds(100,100, 50,50);

JCheckBox checkBox2 = new JCheckBox("Java", true);

checkBox2.setBounds(100,150, 50,50);

f.add(checkBox1);

f.add(checkBox2);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new SCheckBoxExample();

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

Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the


specified array.

JList(ListModel<ary> dataModel) Creates a JList that displays elements from the


specified, non-null, model.

Commonly used Methods:

Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to


listener) the list, to be notified each
time a change to the selection
occurs.

int getSelectedIndex() It is used to return the


smallest selected cell index.

ListModel getModel() It is used to return the data


model that holds a list of items
displayed by the JList
component.

void setListData(Object[] listData) It is used to create a read-only


ListModel from an array of
objects.
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, set the vertical and
horizontal scroll bar policies (respectively).
JScrollPane(Component)

JScrollPane(int, int)

JScrollPane(Component, int, int)

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 must be
one of the following constants defined in
Component getCorner(String)
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.

Ex:Java program to create Scrollpane


import javax.swing.*;
import java.awt.*;
public class JScrollPaneExample
{
JScrollPaneExample()
{
JFrame f = new JFrame("Scroll Pane Example");
f.setSize(500, 500);
f.setVisible(true);
f.getContentPane().setLayout(new FlowLayout());
JTextArea t = new JTextArea(20, 20);
JScrollPane s = new JScrollPane(t);
//
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWA
YS);
//
s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
f.getContentPane().add(s);
}
public static void main(String[] args)
{
new JScrollPaneExample();
}
}
JSplitPane

JSplitPane is used to divide two components. The two components are


divided based on the look and feel implementation, and they can be resized by the
user. If the minimum size of the two components is greater than the size of the split
pane, the divider will not allow you to resize it.

The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using
JSplitPane.VERTICAL_SPLIT. When the user is resizing the components the
minimum size of the components is used to determine the maximum/minimum
position the components can be set to.
import java.awt.*;
import javax.swing.*;
public class JSplitPaneExample
{
JSplitPaneExample()
{
JFrame f= new JFrame("JSplitPane Example");
f.setSize(300, 300);
f.setVisible(true);
f.getContentPane().setLayout(new FlowLayout());
String[] option1 = { "A","B","C","D","E" };
JComboBox cb1 = new JComboBox(option1);
String[] option2 = {"1","2","3","4","5"};
JComboBox cb2 = new JComboBox(option2);
Panel panel1 = new Panel();
JButton b1=new JButton("B1");
panel1.add(cb1);
panel1.add(b1);
Panel panel2 = new Panel();
panel2.add(cb2);
//JSplitPane splitPane = new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
panel1, panel2);
f.getContentPane().add(splitPane);
}
public static void main(String[] args)
{
new JSplitPaneExample();
}
}
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.

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.
import javax.swing.*;
public class TabbedPaneExample
{
JFrame f;
TabbedPaneExample()
{
f=new JFrame();

JButton b1=new JButton("Button1");


JButton b2=new JButton("Button2");
JButton b3=new JButton("Button3");

JPanel p1=new JPanel();


JPanel p2=new JPanel();
JPanel p3=new JPanel();

p1.add(b1);
p2.add(b2);
p3.add(b3);

JTabbedPane tp=new JTabbedPane();


tp.setBounds(50,50,200,200);

tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);

f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new TabbedPaneExample();
}
}
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.
Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

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

JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays the
root node.
import javax.swing.*;

//import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.*;

public class TreeExample

JFrame f;

TreeExample()

f=new JFrame();

DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");

DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");

DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");

style.add(color);

style.add(font);

DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");

DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");

DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");

DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");

color.add(red);
color.add(blue);

color.add(black);

color.add(green);

JTree jt=new JTree(style);

f.add(jt);

f.setSize(200,200);

f.setVisible(true);

public static void main(String[] args)

new TreeExample();

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

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Ex: Java program to create Tables

import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f=new JFrame();
String data[][]={ {"101","Arun", "20000"},
{"102","Deepak","80000"},
{"101","chaitanya","70000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java JDialog
The JDialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a


title and without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with


specified Frame as its owner and an empty title.

JDialog(Frame owner, String title, It is used to create a dialog with the specified
boolean modal) title, owner Frame and modality.
Ex : Java program to create Dialog box

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
public class DialogExample implements ActionListener
{
JDialog d;
DialogExample() {
JFrame f= new JFrame();
JButton b = new JButton ("OK");
d = new JDialog(f , "Dialog Example", false);
d.setLayout( new FlowLayout() );
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(200,200);
d.setVisible(true);
b.addActionListener(this);
}
public void actionPerformed( ActionEvent e )
{
d.setVisible(false);
}
public static void main(String args[])
{
new DialogExample();
}
}
JList:

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

Commonly used Constructors:


Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the


specified array.

Commonly used Methods:


Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be


listener) change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected ce

void setListData(Object[] listData) It is used to create a read-only ListModel fro


objects.
import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

class ListEx extends JFrame

JFrame f;

JList li;

ListEx()

f = new JFrame("frame");

JPanel p=new JPanel();

JLabel l= new JLabel("select the day of the week");

String week[]= { "Monday","Tuesday","Wednesday",

"Thursday","Friday","Saturday","Sunday"};

li= new JList(week);

li.setSelectedIndex(2);

p.add(l);

l.setBounds(50,50,100,50);

l.setForeground(Color.red);

f.add(p);
p.add(li);

li.setBounds(60,60,100,100);

f.setSize(400,400);

f.show();

public static void main(String[] args)

new ListEx();

Java Swing Layouts :

FlowLayout
The FlowLayout arranges the components in a directional flow,
either from left to right or from right to left. Normally all components are
set to one row, according to the order of different components. If all
components can not be fit into one row, it will start a new row and fit the
rest in.
To construct a FlowLayout , three options could be chosen:
1.FlowLayout():
construct a new FlowLayout object with center alignment and horizontal
and vertical gap to be default size of 5 pixels.
FlowLayout(int align):
construct similar object with different settings on alignment
FlowLayout(int align, int hgap, int vgap):
construct similar object with different settings on alignment and gaps
between components.
For the constructor with the alignment settings, the possible values could
be: LEFT, RIGHT, CENTER, LEADING and TRAILING .

Ex :A Java swing FlowLayout example

import javax.swing.*;

import java.awt.*

public class FlowLayoutExample

public static void main(String[] args)

JFrame frame = new JFrame("Layout");

JButton jb1 = new JButton("Button 1");

JButton jb2 = new JButton("Button 2");

JButton jb3 = new JButton("Button 3");

// Define the panel to hold the buttons

JPanel panel = new JPanel();

panel.setLayout(new FlowLayout());

panel.add(jb1);

panel.add(jb2);
panel.add(jb3);

// Set the window to be visible as the default to be false

frame.add(panel);

frame.pack();

frame.setVisible(true);

BorderLayout:
A BorderLayout lays out a container, arranging its components to fit
into five regions: NORTH, SOUTH, EAST, WEST and CENTER . For
each region, it may contain no more than one component. When adding
different components, you need to specify the orientation of it to be the one of
the five regions.

For BorderLayout , it can be constructed like below:

 BorderLayout(): construct a border layout with no gaps between components.


 BorderLayout(int hgap, int vgap): construct a border layout with specified
gaps between components.

CardLayout
For CardLayout , it treats the components as a stack and every time, what
you can see is only one component. That’s why it’s called CardLayout .
To demonstrate how to use CardLayout , three buttons have been
constructed. We can click the button and get the next button, then click it again,
getting the next one.

The following code is to show how to achieve this CardLayout .


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

public class CardLayoutExample extends JFrame implements ActionListener


{

public CardLayoutExample() {
getContentPane().setLayout(new CardLayout(40, 30));

// Define new buttons


jb1 = new JButton("Button 1");
jb2 = new JButton("Button 2");
jb3 = new JButton("Button 3");

jb1.addActionListener(this);
jb2.addActionListener(this);
jb3.addActionListener(this);

add(jb1);
add(jb2);
add(jb3);
setVisible(true);
setSize(300,300);

public static void main(String[] args) {


// Create and set up a frame window
CardLayoutExample cl = new CardLayoutExample();

}
// Action listener
public void actionPerformed(ActionEvent e) {
card.next(c);
}

GridLayout

The GridLayout manager is used to lay out the components in a rectangle grid, which has
been divided into equal-sized rectangles and one component is placed in each rectangle. It can
constructed with following methods:
GridLayout(): construct a grid layout with one column per component in a single row.
 GridLayout(int row, int col): construct a grid layout with specified numbers of rows and
columns.
 GridLayout(int row, int col, int hgap, int vgap): construct a grid layout with specified
rows, columns and gaps between components.
With the following code, we can create a grid layout object with two rows, three columns.
Similarly, we can change the order of two and three to create three rows, two columns grid
layout object.

GridBagLayout
GridBagLayout is a more flexible layout manager, which allows the
components to be vertical, horizontal, without specifying the components to be the
same size. Each GridLayout object holds a dynamic rectangular grid of cells.
Each component is associated with an instance of GridBagConstraints .
The GridBagConstraints decides where the component to be displayed and
how the component should be positioned.

You might also like