Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
29 views84 pages

OOPJ UNIT - 5 Ece

Oops Java unit 5 _r18 ece 3_2sem all topics from unit 5 important topics

Uploaded by

polavenitharun48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views84 pages

OOPJ UNIT - 5 Ece

Oops Java unit 5 _r18 ece 3_2sem all topics from unit 5 important topics

Uploaded by

polavenitharun48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

OOPJ

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.


Java Applet

• Applet is a special type of program that is embedded in the webpage to generate

the dynamic content.

• It runs inside the browser and works at client side.


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.


Drawback of Applet

• Plugin is required at client browser to execute applet.

• A plugin is a software add-on that is installed on a program, enhancing its capabilities. For

example, if you wanted to watch a video on a website, you may need a plugin to do so. If

the plugin is not installed, your browser will not understand how to play the video.
Hierarchy of Applet

As displayed in this diagram, Applet class


extends Panel. Panel class extends Container
which is the subclass of Component.
Lifecycle of Java Applet

1.Applet is initialized.
2.Applet is started.
3.Applet is painted.
4.Applet is stopped.
5.Applet is destroyed.
Life cycle of an applet :
• It is important to understand the order in which the various methods shown in the
above image are called. When an applet begins, the following methods are called, in
this sequence:

1.init( )

2.start( )

3.paint( )

• When an applet is terminated, the following sequence of method calls takes place:

1.stop( )

2.destroy( )
Let’s look more closely at these methods:-

1.init( ) : The init( ) method is the first method to be called. This is where you should initialize

variables. This method is called only once during the run time of your applet.

2.start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it

has been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded

whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So,

if a user leaves a web page and comes back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based

applet’s output must be redrawn. This situation can occur for several

reasons. For example, the window in which the applet is running may be

overwritten by another window and then uncovered. Or the applet window

may be minimized and then restored.paint( ) is also called when the

applet begins execution. Whatever the cause, whenever the applet must

redraw its output, paint( ) is called.


• The paint( ) method has one parameter of type Graphics. This parameter will contain the

graphics context, which describes the graphics environment in which the applet is running.

This context is used whenever output to the applet is required.

Note: This is the only method among all the method mention above, which is parametrised.

It’s prototype is

public void paint(Graphics g)

where g is an object reference of class Graphic.


4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document

containing the applet—when it goes to another page, for example. When stop( ) is called,

the applet is probably running. You should use stop( ) to suspend threads that don’t need to

run when the applet is not visible. You can restart them when start( ) is called if the user

returns to the page.

5. destroy( ) : The destroy( ) method is called when the environment determines that your

applet needs to be removed completely from memory. At this point, you should free up any

resources the applet may be using. The stop( ) method is always called before destroy( ).
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.
Who is responsible to manage the life cycle of an applet?

• Java Plug-in software.


How to run an Applet?

• There are two ways to run an applet

1.By html file.

2.By appletViewer tool (for testing purpose).


Simple example of Applet by html
file
• To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.

//Simple.java
import java.applet.Applet;
import java.awt.Graphics;
public class Simple extends Applet
{ Note: class must be public because its object is
public void paint(Graphics g) created by Java Plugin software that resides on
{ the browser.
g.drawString(" A simple Applet ", 20, 20);
}
}
myapplet.html

<html>
<body>
<applet code="
Simple.class" width=“20" height=“20">
</applet>
</body>
</html>
Output:
Restrictions imposed on Java
applets
Due to security reasons , the following restrictions are
imposed on Java applets:
1.An applet cannot load libraries or define native
methods.
2.An applet cannot ordinarily read or write files on the
execution host.
3.An applet cannot read certain system properties.
4.An applet cannot make network connections except to
the host that it came from.
5.An applet cannot start any program on the host that’s
Difference between Applet and Application

• 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
Applets are small Java programs that are designed to be included
Applications are just like a Java programs that can be execute with the HTML web document. They require a Java-enabled web
independently without using the web browser. browser for execution.

Application program requires a main function for its execution. Applet does not require a main function for its execution.

Java application programs have the full access to the local file system
and network. Applets don’t have local disk and network access.

Applets can only access the browser specific services. They don’t
Applications can access all kinds of resources available on the system. have access to the local system.

Applications can execute the programs from the local system. Applets cannot execute programs from the local machine.

An application program is needed to perform some task directly for


the user. An applet program is needed to perform small tasks or the part of it.
Types of Applets in Java
• A special type of Java program that runs in a Web browser is referred to
as Applet. It has less response time because it works on the client-side. It is much
secured executed by the browser under any of the platforms such as Windows,
Linux and Mac OS etc. There are two types of applets that a web page can
contain.

1.Local Applet

2.Remote Applet
Local Applet
• Local Applet is written on our own, and then we will embed it into web pages. Local
Applet is developed locally and stored in the local system.

• A web page doesn't need the get the information from the internet when it finds the local
Applet in the system.

• It is specified or defined by the file name or pathname.

• There are two attributes used in defining an applet, i.e., the codebase that specifies the
path name and code that defined the name of the file that contains Applet's code.
Remote Applet

• A remote applet is designed and developed by another developer.

• It is located or available on a remote computer that is connected to the internet.

• In order to run the applet stored in the remote computer, our system is connected to the
internet then we can download run it.

• In order to locate and load a remote applet, we must know the applet's address on the
web that is referred to as Uniform Recourse Locator(URL).
Difference Between Local Applet and Remote Applet
Local Applet Remote Applet

There is no need to define the Applet's URL in Local We need to define the Applet's URL in Remote
Applet. Applet.

Local Applet is available on our computer. Remote Applet is not available on our computer.

In order to use it or access it, we don't need Internet In order to use it or access it on our computer, we
Connection. need an Internet Connection.

It is written on our own and then embedded into the It was written by another developer.
web pages.

We don't need to download it. It is available on a remote computer, so we need


to download it to our system.
The Applet Class
• Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
• These include methods that do the following −
• Get applet parameters
• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet
Invoking an Applet
• An applet may be invoked by embedding directives in an HTML file and viewing the file through an

applet viewer or Java-enabled browser.

• The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that

invokes the "Hello, World" applet −

<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
</hr>
Passing Parameters to Applets

Steps to accomplish this task

• To pass the parameters to the Applet we need to use the param attribute

of <applet> tag.

• To retrieve a parameter's value, we need to use the getParameter() method

of Applet class.
Signature of the getParamter()
method

public String getParameter(String name)

• Method takes a String argument name, which represents the name of the
parameter which was specified with the param attribute in the <applet> tag.

• Method returns the value of the name parameter(if it was defined) else null is
returned.
Simple example of Passing Parameters to Applets
import java.awt.*;
import java.applet.*;

/*
<applet code="Applet8" width="400" height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination" value="California">
</applet>
*/

public class Applet8 extends Applet


{
String name;
String age;
String sport;
String food;
String fruit;
String destination;
public void init()
{
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
}

public void paint(Graphics g)


{
g.drawString("Reading parameters passed to this applet -", 20, 20);
g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60);
g.drawString("Favorite fruit -" + fruit, 20, 80);
g.drawString("Favorite food -" + food, 20, 100);
g.drawString("Favorite destination -" + name, 20, 120);
g.drawString("Favorite sport -" + sport, 20, 140);
}
}
Output:
Java Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.

• Unlike AWT, Java Swing provides platform-independent and lightweight


components.

• The javax.swing package provides classes for java swing API such as
JButton,
The JTextField,
Java Foundation JTextArea,
Classes (JFC) areJRadioButton, JCheckbox,
a set of GUI components JMenu,
which
simplify the development
JColorChooser etc. of desktop applications.
Difference between AWT and Swing

No. Java AWT Java Swing


1) AWT components are platform- Java swing components
dependent. are platform-independent.
2) AWT components Swing components
are heavyweight. are lightweight.
3) AWT doesn't support Swing supports pluggable look
pluggable look and feel. and feel.
4) AWT provides less Swing provides more powerful
components than Swing. components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
5) AWT doesn't follows Swing follows MVC.
MVC(Model View Controller)
where model represents data,
Hierarchy of Java Swing classes
Commonly used Methods of Component class

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
m) component.
public void setVisible(boolean b) sets the visibility of the component. It
is by default false.
Java Swing Examples

There are two ways to create a frame:

• By creating the object of Frame class (association)


• By extending Frame class (inheritance)

We can write the code of swing inside the main(),


constructor or any other method.
Example of Swing by Association inside constructor

import javax.swing.*;
public class Simple { Output:
Simple(){
JFrame 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();
}
}
Simple example of Swing by inheritance

import javax.swing.*;
public class Simple2 extends Jframe Output:
{
//inheriting JFrame
JFrame f;
Simple2()
{
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new Simple2();
}
}
Limitations of AWT

• The AWT defines a basic set of controls, windows, and dialog boxes that
support a usable, but limited graphical interface.
• One reason for the limited nature of the AWT is that it translates its various
visual components into their corresponding, platform-specific equivalents or
peers.
• This means that the look and feel of a component is defined by the platform,
not by java.
• Because the AWT components use native code resources, they are referred to
as heavy weight. The use of native peers led to several problems.
• First, 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.

• Second, the look and feel of each component was fixed and could not be changed.

• Third, the use of heavyweight components caused some frustrating restrictions.

• Due to these limitations Swing came and was integrated to java.

• Swing is built on the AWT. Two key Swing features are:

1. Swing components are light weight,

2. Swing supports a pluggable look and feel.


MVC Architecture

Swing uses the model-view-controller architecture (MVC) as the fundamental

design behind each of its components. Essentially, MVC breaks GUI

components into three elements. Each of these elements plays a

crucial role in how the component behaves.


Model

A model is an abstraction of something that is presented to the user. The models

provided by Swing fall into two general categories: GUI-state models and application-

data models. GUI state models are interfaces that define the visual status of a GUI

control, such as whether a button is pressed or armed like ButtonModel. An application-

data model is an interface that represents some quantifiable data that the UI presents

to the user, such as the value of a cell in a table like TableModel.


View

The view is a UI component that is responsible for presenting data to the user. Thus it

is responsible for all UI dependent issues like layout, drawing, etc. JTable is a good

example for the view.


Controller

A controller encapsulates the application code that is executed in order to an user

interaction (mouse motion, mouse click, key press, etc.). Controllers might need input for

their execution and they produce output. They read their input from models and update

models as result of the execution. In swing a controller is normally implemented by an

ActionListener or Action.
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.

Constructor
Constructor Description
JComponent() Default JComponent constructor.
Useful Methods
Modifier and Type Method Description
void setActionMap(ActionMap am) It sets the ActionMap to am.
void setBackground(Color bg) It sets the background color of this component.

void setFont(Font font) It sets the font for this component.


void setMaximumSize(Dimension It sets the maximum size of this component to a constant
maximumSize) value.
void setMinimumSize(Dimension It sets the minimum size of this component to a constant
minimumSize) value.
protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this component.

void setVisible(boolean aFlag) It makes the component visible or invisible.

void setForeground(Color fg) It sets the foreground color of this component.

String getToolTipText(MouseEvent event) It returns the string to be used as the tooltip for event.

Container getTopLevelAncestor() It returns the top-level ancestor of this component (either


the containing Window or Applet), or null if this component
has not been added to any container.

TransferHandler getTransferHandler() It gets the transferHandler property.


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

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

JFrame(GraphicsConfiguration gc) It creates a Frame in the specified


GraphicsConfiguration of 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
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen
device.
Useful Methods
Modifier and Type Method Description
protected void addImpl(Component comp, Object Adds the specified child Component.
constraints, int index)
protected createRootPane() Called by the constructor methods to
JRootPane create the default rootPane.
protected void frameInit() Called by the constructors to init the
JFrame properly.
void setContentPane(Containe contentPane) It sets the contentPane property
static void setDefaultLookAndFeelDecorated(boolea Provides a hint as to whether or not
n defaultLookAndFeelDecorated) newly created JFrames should have
their Window decorations (such as
borders, widgets to close the window,
title...) provided by the current look and
feel.
void setIconImage(Image image) It sets the image to be displayed as the
icon for this window.
void setJMenuBar(JMenuBar menubar) It sets the menubar for this frame.
void setLayeredPane(JLayeredPane It sets the layeredPane property.
layeredPane)
JRootPane getRootPane() It returns the rootPane object for this
frame.
Icons in Swing
• The setIconImage() method of Frame class is used to
change the icon of Frame or Window. It changes the
icon which is displayed at the left side of Frame or
Window.
• The Toolkit class is used to get instance of Image class
in AWT and Swing.
• Toolkit class is the abstract super class of every
implementation in the Abstract Window Toolkit(AWT).
Subclasses of Toolkit are used to bind various
components. It inherits Object class.
Example to change TitleBar icon in Java AWT

import javax.swing.*;
class IconExample
{
IconExample()
{
Output:
JFrame f=new JFrame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[])
{
new IconExample();
}
Java JLabel
• The object of JLabel class is a component for placing text in a container. It
is used to display a single line of read only text. The text can be changed
by an application but a user cannot edit it directly. It inherits JComponent
class.

• JLabel class declaration

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

public class JLabel extends JComponent implements SwingConstants, A


ccessible
Java JLabel Example

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

• The object of a JTextField class is a text component that allows


the editing of a single line text. It inherits JTextComponent class.

• JTextField class declaration

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

public class JTextField extends JTextComponent implements S


wingConstants
Java JTextField Example

import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{ Output:
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JButton
• The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action
when the button is pushed. It inherits AbstractButton class.

• JButton class declaration

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

public class JButton extends AbstractButton implements Accessible


Java JButton Example

import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) { Output:

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


JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java 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.

public class JCheckBox extends JToggleButton implements Accessible


Java JCheckBox Example

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example"); Output:
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Java JRadioButton

• The JRadioButton class is used to create a radio button. It is used to


choose one option from multiple options. It is widely used in exam
systems or quiz.

• It should be added in ButtonGroup to select one radio button only.

• JRadioButton class declaration

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

public class JRadioButton extends JToggleButton implements Access


ible
Java JRadioButton Example

import javax.swing.*;
public class RadioButtonExample
{
RadioButtonExample()
{ Output:
JFrame f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");

r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
Java 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.

public class JComboBox extends JComponent implements ItemSelectable,


ListDataListener, ActionListener
Java JComboBox Example

import javax.swing.*;
public class ComboBoxExample {

ComboBoxExample(){
Output:
JFrame f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","
Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{
new ComboBoxExample();
}
}
Java 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.

• JTabbedPane class declaration

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

public class JTabbedPane extends JComponent implements Serializable,

Accessible, SwingConstants
Java JTabbedPane Example

import javax.swing.*;
public class TabbedPaneExample {
TabbedPaneExample(){
JFrame f=new JFrame();
JTextArea ta=new JTextArea(200,200); Output:
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
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();
}}
Java 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
JScrollPane(Component) scroll bar policies (respectively).

JScrollPane(int, int)

JScrollPane(Component, int,
int)
Useful Methods

Modifier Method Description


void setColumnHeaderView(Compone It sets the column header for the
nt) 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.
Component getCorner(String) The int parameter specifies which
corner and 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,
JScrollPane Example

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;

public class JScrollPaneExample


{
private static final long serialVersionUID = 1L;
private static void createAndShowGUI()
{
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Exampl
e");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
SE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());

JTextArea textArea = new JTextArea(20, 20);


JScrollPane s = new JScrollPane(textArea);

s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Output:
frame.getContentPane().add(s);
}
public static void main(String[] args)
{

javax.swing.SwingUtilities.invokeLater(new Runnable() )
{
public void run()
{
createAndShowGUI();
}
});
}
}
Java 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.

public class JTree extends JComponent implements Scrollable, Accessi


ble
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.
Java JTree Example

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
TreeExample()
{
JFrame 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("bl
ack");
DefaultMutableTreeNode green=new DefaultMutableTreeNode(
"green");
color.add(red); color.add(blue); color.add(black); color.add(gree
n);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
Output:
Java 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, Creates a table with the
Object[] columns) specified data.
Java JTable Example

import javax.swing.*;
public class TableExample
{

TableExample() Output:
{
JFrame f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
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();
}
}

You might also like