0% found this document useful (0 votes)
24 views32 pages

Java Unit5

Uploaded by

vinodkethavath03
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)
24 views32 pages

Java Unit5

Uploaded by

vinodkethavath03
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/ 32

Unit-5

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.

Advantages of Applet

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

Applets and Applications

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 document. They require a Java-
web browser. enabled web browser for execution.

Application program requires a Applet does not require a main function


main function for its execution. for its execution.

Java application programs have


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

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

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

An application program is needed


to perform some task directly for An applet program is needed to perform
the user. small tasks or the part of it.
Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet

The java.applet.Applet class provides 4 life cycle methods and java.awt.Component


class provides 1 life cycle method for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.


1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
How to run an Applet?

There are two ways to run an applet


1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

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

import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet",20,20);
}
}

myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag
in comment and compile it. After that run it by: appletviewer First.java. Now Html
file is not required but it is for testing purpose only.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter().

Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:

import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}

myapplet.html

<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Types of Applets
A special type of Java program that runs in a Web browser is referred to as Applet.
It has less response time because it works on the client-side. It is much secured
executed by the browser under any of the platforms such as Windows, Linux and
Mac OS etc. There are two types of applets that a web page can contain.

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.

Specifying Local applet


<applet
codebase = "tictactoe"
code = "FaceApplet.class"
width = 120
height = 120>
</applet>
Let's take an example of Local applet to understand how we can create it and
embedded it into web page.

1.First, we will create a Local Applet for embedding in a web page.

2.After that, we will add that Local Applet to the web page.
FaceApplet.java

//Import packages and classes


import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
//Creating FaceApplet class that extends Applet
public class FaceApplet extends Applet
{
//paint() method starts
public void paint(Graphics g){
//Creating graphical object
g.setColor(Color.red);
g.drawString("Welcome", 50, 50);
g.drawLine(20, 30, 20, 300);
g.drawRect(70, 100, 30, 30);
g.fillRect(170, 100, 30, 30);
g.drawOval(70, 200, 30, 30);
g.setColor(Color.pink);
g.fillOval(170, 200, 30, 30);
g.drawArc(90, 150, 30, 30, 30, 270);
g.fillArc(270, 150, 30, 30, 0, 180);
}
}

Remote Applet
A remote applet is designed and developed by another developer. It is located or
available on a remote computer that is connected to the internet. In order to run
the applet stored in the remote computer, our system is connected to the internet
then we can download run it. In order to locate and load a remote applet, we must
know the applet's address on the web that is referred to as Uniform Recourse
Locator(URL).
Specifying Remote applet
<applet
codebase = "http://www.jbrecnotes.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>

Difference Between Local Applet and Remote Applet


The following table describes the key differences between Local applet and Remote
applet.

Local Applet Remote Applet


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

Applet's URL in Local Applet. Remote Applet.

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

computer. computer.

In order to use it or access it, we In order to use it or access it on our

don't need Internet Connection. computer, we need an Internet Connection.

It is written on our own and then


It was written by another developer.
embedded into the web pages.

It is available on a remote computer, so we


We don't need to download it.
need to download it to our system.
Java Swing Components and Containers

A component is an independent visual control and Java Swing Framework contains a


large set of these components which provide rich functionalities and allow high level
of customization. They all are derived from JComponent class. All these components
are lightweight components. This class provides some common functionality like
pluggable look and feel, support for accessibility, drag and drop, layout, etc.

A container holds a group of components. It provides a space where a component


can be managed and displayed. Containers are of two types:

1. Top level Containers

o It inherits Component and Container of AWT.

o It cannot be contained within other containers.

o Heavyweight.

o Example: JFrame, JDialog, JApplet

2. Lightweight Containers

o It inherits JComponent class.

o It is a general purpose container.

o It can be used to organize related components together.


o Example: JPanel

JPanel:

The class JPanel is a generic lightweight container.


Class Constructors:

1. JPanel(): Creates a new JPanel with a double buffer and a flow layout.
2. JPanel(boolean isDoubleBuffered): Creates a new JPanel with FlowLayout and
the specified buffering strategy.
3. JPanel(LayoutManager layout): Creates a new buffered JPanel with the
specified layout manager.
4. JPanel(LayoutManager layout, boolean isDoubleBuffered): Creates a new JPanel
with the specified layout manager and buffering strategy.
import javax.swing.*;
class JPanelExample {
JPanelExample(){
JFrame frame = new JFrame("Panel Example"); //create a frame
JPanel panel = new JPanel(); //Create JPanel Object
panel.setBounds(40,70,100,100); //set dimensions for Panel
JButton b = new JButton("ButtonInPanel"); //create JButton object
b.setBounds(60,50,80,40); //set dimensions for button
panel.add(b); //add button to the panel
frame.add(panel); //add panel to frame
frame.setSize(400,400);
frame.setLayout(null);
frame.setVisible(true);
}

}
public class Main {
public static void main(String[] args) {
new JPanelExample(); //create an object of FrameInherited class
}
}

JFrame:
The class JFrame is an extended version of java.awt.Frame that adds support for the
JFC/Swing component architecture.
Class Constructors:

 JFrame(): Constructs a new frame that is initially invisible.


 JFrame(GraphicsConfiguration gc): Creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank title.
 JFrame(String title): Creates a new, initially invisible Frame with the specified
title.

 JFrame(String title, GraphicsConfiguration gc): Creates a JFrame with the


specified title and the specified GraphicsConfiguration of a screen device.

import javax.swing.*;

class FrameInherited extends JFrame{ //inherit from JFrame class


JFrame f;
FrameInherited(){
JButton b=new JButton("JFrame_Button");//create button object
b.setBounds(100,50,150, 40);

add(b);//add button on frame


setSize(300,200);
setLayout(null);
setVisible(true);
}
}
public class Main {
public static void main(String[] args) {
new FrameInherited(); //create an object of FrameInherited class
}
}

JWindow
The class JWindow is a container that can be displayed but does not have the title
bar or window-management buttons.
Field

Class Constructors

 JWindow(): Creates a window with no specified owner.


 JWindow(Frame owner): Creates a window with the specified owner frame.
 JWindow(GraphicsConfiguration gc): Creates a window with the specified
GraphicsConfiguration of a screen device.
 JWindow(Window owner): Creates a window with the specified owner
window.
 JWindow(Window owner, GraphicsConfiguration gc): Creates a window with
the specified owner window and GraphicsConfiguration of a screen device.
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JWindow;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyJWindowExample {


public static void main(String[] args) {

JWindow window = new Jwindow(); // Create an instance of JWindow


JLabel label = new JLabel("This is a JWindow example"); // Create a JLabel
JButton closeButton = new JButton("Close Window"); // Create a JButton
// Add an ActionListener to the close button
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Close the window when the button is clicked
window.dispose();
}
});

// Add the label and close button to the content pane


window.getContentPane().add(label, BorderLayout.CENTER);
window.getContentPane().add(closeButton, BorderLayout.SOUTH);
window.setSize(300, 150); // Set the size of the window
window.setLocationRelativeTo(null); // Center the window on the screen
window.setVisible(true); // Make the window visible
}
}

The JApplet Class


JApplet is a simple extension of java.applet.Applet to use when creating Swing
programs designed to be used in a web browser (or appletviewer ). As a direct
subclass of Applet, JApplet is used in much the same way, with the init( ) , start( ),
and stop( ) methods still playing critical roles.
// SimpleApplet.java
//
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;

public class SimpleApplet extends JApplet {


public void init( ) {
JPanel p = new JPanel( );
p.setLayout(new GridLayout(2, 2, 2, 2));
p.add(new JLabel("Username"));
p.add(new JTextField( ));
p.add(new JLabel("Password"));
p.add(new JPasswordField( ));
Container content = getContentPane( );
content.setLayout(new GridBagLayout( )); // Used to center the panel
content.add(p);
}
}

Icons
Many Swing components, such as labels, buttons, and tabbed panes, can be
decorated with an icon — a fixed-sized picture. An icon is an object that adheres
to the Icon interface. Swing provides a particularly useful implementation of the
Icon interface: ImageIcon, which paints an icon from a GIF, JPEG, or PNG
image.
The program uses one image icon to contain and paint the yellow splats. One
statement creates the image icon and two more statements include the image
icon on each of the two labels:
ImageIcon icon = createImageIcon("images/middle.gif",
"a pretty but meaningless splat");
label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
label3 = new Jlabel(icon);

Example:

import javax.swing.ImageIcon;

import javax.swing.*;
public class ImageIconExample {

public static void main(String[] args) {

// Example usage of createImageIcon

ImageIcon icon = createImageIcon("b2.png", "Description");

if (icon != null) {

// Use the ImageIcon in your Swing components

// For example, set it as an icon for a JLabel

JLabel label = new JLabel("Hello, World!", icon, JLabel.CENTER);

JFrame frame = new JFrame("ImageIcon Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(label);

frame.setSize(300, 200);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

} else {

System.err.println("Could not load the image.");

// Utility method to create an ImageIcon

protected static ImageIcon createImageIcon(String path, String


description) {

java.net.URL imgURL = ImageIconExample.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL, description);

} else {
System.err.println("Couldn't find file: " + path);

return null;

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

Example
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas
{
public void paint(Graphics g)
{
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);

}
public static void main(String[] args)
{
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}

}
Output:

Exploring Swing Controls


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.
Commonly used Methods

Methods Description

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

void setText(String text) It defines the single line of text this component
will display.

void It sets the alignment of the label's contents


setHorizontalAlignment(int along the X axis.
alignment)

Icon getIcon() It returns the graphic image that the label


displays.

int getHorizontalAlignment() It returns the alignment of the label's contents


along the X axis.

Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
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);
}
}

Output:
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 Methods:


Methods Description

void It is used to add the specified action listener


addActionListener(ActionListener to receive action events from this textfield.
l)

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


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

Example
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 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);
}
}

Output:
JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the


button.

Icon getIcon() It is used to get the Icon of the button.

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


button.

void addActionListener It is used to add the action listener to


(ActionListener a) this object.

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);
}
}

Output:
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.

Methods
Modifier Method Description
and Type

AccessibleContex getAccessibleContext It gets the AccessibleContext associated


t () with this JToggleButton.

String getUIClassID() It returns a string that specifies the


name of the l&f class that renders this
component.

protected String paramString() It returns a string representation of


this JToggleButton.

void updateUI() It resets the UI property to a value


from the current look and feel.
Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener


{
public static void main(String[] args)
{
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample()
{
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton()
{
button = new JToggleButton("ON");
add(button);
}
private void setAction()
{
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve)
{
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}
Output:

JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or
from "off" to "on ".It inherits JToggleButton class.

Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample()
{
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 CheckBoxExample();
}
}
Output:

JRadioButton
 The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
 It should be added in ButtonGroup to select one radio button only.

Example
import javax.swing.*;
public class RadioButtonExample
{

RadioButtonExample()
{
JFrame f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
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();
}
}

Output:

JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking
on a tab with a given title or icon. It inherits JComponent class.

Example
import javax.swing.*;
public class TabbedPaneExample
{
TabbedPaneExample()
{
JFrame f=new JFrame();
JTextArea ta=new JTextArea(200,200);
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();
}
}
Output:

JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose
size can change dynamically.

Useful Methods
Modifier Method Description

void SetColumnHeaderView It sets the column header for the scroll


(Component) 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
Componen getCorner(String) be one of the following constants defined
t in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

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

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 Example");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCR
OLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBA
R_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Output:
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 Methods:


Methods Description

Void It is used to add a listener to the


addListSelectionListener(ListSelectionListe list, to be notified each time a
ner listener) 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.

Example
import javax.swing.*;
public class ListExample
{
ListExample()
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:

JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits JComponent class.

Commonly used Methods:


Methods Description

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

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


list.

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


the list.

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


JComboBox is editable.

void It is used to add the ActionListener.


addActionListener(ActionListener a)

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

Example
import javax.swing.*;
public class ComboBoxExample
{
ComboBoxExample()
{
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();
}
}
Output:

Swing Menus
JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may
have several menus.
The object of JMenu class is a pull down menu component which is displayed from
the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in
a menu must belong to the JMenuItem or any of its subclass.

JMenuItem and JMenu Example


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample()
{
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}

Output:

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.

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

Output:

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.
Commonly used Constructors:
Constructor Description
JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as

value) the child of a new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which

root) displays the root node.

Java JTree Example

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
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();
}}
Output:
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.

JTable class declaration

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

Commonly used Constructors:


Constructor Description
JTable() Creates a table with empty cells.

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

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

You might also like