0% found this document useful (0 votes)
25 views98 pages

Swing

Advance java programming 2nd chapter important notes.

Uploaded by

harshchauhan0704
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)
25 views98 pages

Swing

Advance java programming 2nd chapter important notes.

Uploaded by

harshchauhan0704
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/ 98

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.
Difference between AWT and Swing
AWT Swing
AWT components are platform- Java swing components are platform-
dependent. independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look Swing supports pluggable look and
and feel. feel.
AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
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.

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

MADHAVI 1
Java Swing

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

MADHAVI 2
Java Swing

Simple Java Swing Example


import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
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
}
}
Output:

Example of Swing by Association inside constructor


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();
} }
MADHAVI 3
Java Swing

Output:

Simple example of Swing by inheritance


import javax.swing.*;
public class Simple2 extends JFrame{//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();
}}
Output:

MADHAVI 4
Java Swing

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
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and
icon.
JButton(String s) It creates a button with the
specified text.
JButton(Icon i) It creates a button with the
specified icon object.
Commonly used Methods of AbstractButton class:
Methods Description
void setText(String s) It is used to set specified text on
button
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable
the button.
void setIcon(Icon b) It is used to set the specified
Icon on the button.
Icon getIcon() It is used to get the Icon of the
button.
void setMnemonic(int a) It is used to set the mnemonic
on the button.
void It is used to add the action
addActionListener(ActionListener a) listener to this object.
Java 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);
MADHAVI 5
Java Swing

}
}
Output:

Java JButton Example with ActionListener


import java.awt.event.*;
import javax.swing.*;
public class ButtonExample1 {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
} });
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
Output:

MADHAVI 6
Java Swing

Example of displaying image on the button:


import javax.swing.*;
public class ButtonExample2{
ButtonExample2(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample2();
}
}
Output:

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
public class JLabel extends JComponent implements SwingConstants,
Accessible

MADHAVI 7
Java Swing

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
horizontalAlignment) specified text, image, and
horizontal alignment.
Commonly used Methods:
Methods Description
String getText() it returns the text string that a
label displays.
void setText(String text) It defines the single line of text
this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's
alignment) contents along the X axis.
Icon getIcon() It returns the graphic image that
the label displays.
int getHorizontalAlignment() It returns the alignment of the
label's contents along the X axis.
Java JLabel Example
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);
} }
MADHAVI 8
Java Swing

Output:

Java JLabel Example with ActionListener


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample1 extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample1(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample1();
}}

MADHAVI 9
Java Swing

Output:

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
public class JTextField extends JTextComponent implements
SwingConstants
Commonly used Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized
with the specified text.
JTextField(String text, int Creates a new TextField initialized
columns) 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 It is used to add the specified
addActionListener(ActionListener l) 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
removeActionListener(ActionListener specified action listener so that
l)
1
MADHAVI
0
Java Swing

it no longer receives action


events from this textfield.
Java JTextField 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:

Java JTextField Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample1 implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
1
MADHAVI
1
Java Swing

TextFieldExample1(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample1();
}}

1
MADHAVI
2
Java Swing

Output:

Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It
allows the editing of multiple line text. It inherits JTextComponent class
JTextArea class declaration
public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no
text initially.
JTextArea(String s) Creates a text area that displays
specified text initially.
JTextArea(int row, int column) Creates a text area with the
specified number of rows and
columns that displays no text
initially.
JTextArea(String s, int row, int Creates a text area with the
column) specified number of rows and
columns that displays specified
text.
Commonly used Methods:
Methods Description
void setRows(int rows) It is used to set specified number
of rows.
void setColumns(int cols) It is used to set specified number
of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified
text on the specified position.
void append(String s) It is used to append the given text
to the end of the document.

1
MADHAVI
3
Java Swing

Java JTextArea Example


import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to ITTEAMWORK");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:

Java JTextArea Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample1 implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample1() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
1
MADHAVI
4
Java Swing

l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample1();
}
}
Output:

1
MADHAVI
5
Java Swing

Java JPasswordField
The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text. It inherits
JTextField class.
JPasswordField class declaration
public class JPasswordField extends JTextField
Commonly used Constructors:
Constructor Description
JPasswordField() Constructs a new JPasswordField,
with a default document, null
starting text string, and 0 column
width.
JPasswordField(int columns) Constructs a new empty
JPasswordField with the specified
number of columns.
JPasswordField(String text) Constructs a new JPasswordField
initialized with the specified text.
JPasswordField(String text, int Construct a new JPasswordField
columns) initialized with the specified text
and columns.
Java JPasswordField Example
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
} }
Output:

1
MADHAVI
6
Java Swing

Java JPasswordField Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample1 {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
final JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
JLabel l2=new JLabel("Password:");
l2.setBounds(20,75, 80,30);
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
final JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b);
f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
}); } }
Output:

1
MADHAVI
7
Java Swing

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
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JCheckBox() 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
selected) specifies 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
getAccessibleContext() AccessibleContext associated
with this JCheckBox.
protected String paramString() It returns a string representation of
this JCheckBox.
Java JCheckBox 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);
1
MADHAVI
8
Java Swing

f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:

Java JCheckBox Example with ItemListener


import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample1
{
CheckBoxExample1(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

1
MADHAVI
9
Java Swing

checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample1();
}
}
Output:

Java JCheckBox Example: Food Order


import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample2 extends JFrame implements
ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample2(){
l=new JLabel("Food Ordering System");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");

2
MADHAVI
0
Java Swing

cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample2();
}
}

2
MADHAVI
1
Java Swing

Output:

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
public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JRadioButton() Creates an unselected radio button
with no text.
JRadioButton(String s) Creates an unselected radio button
with specified text.
JRadioButton(String s, boolean Creates a radio button with the
selected) specified text and selected status.
Commonly used Methods:
Methods Description
void setText(String s) It is used to set specified text on
button.
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable
the button.

2
MADHAVI
2
Java Swing

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 It is used to add the action
addActionListener(ActionListener a) listener to this object.
Java JRadioButton Example
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
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();
}
}
Output:

2
MADHAVI
3
Java Swing

Java JRadioButton Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample1 extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample1(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male."); }
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female."); } }
public static void main(String args[]){
new RadioButtonExample1();
}}
Output:

2
MADHAVI
4
Java Swing

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
JComponentclass.
JComboBox class declaration
public class JComboBox extends JComponent implements
ItemSelectable, ListDataListener, ActionListener, Accessible
Commonly used Constructors:
Constructor Description
JComboBox() Creates a JComboBox with a
default data model.
JComboBox(Object[] items) Creates a JComboBox that
contains the elements in the
specified array.
JComboBox(Vector<?> items) Creates a JComboBox that
contains the elements in the
specified Vector.
Commonly used Methods:
Methods Description
void addItem(Object anObject) It is used to add an item to the item
list.
void removeItem(Object anObject) It is used to delete an item to the item
list.
void removeAllItems() It is used to remove all the items from
the list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void It is used to add the ActionListener.
addActionListener(ActionListener a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
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);
2
MADHAVI
5
Java Swing

f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:

Java JComboBox Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample1 {
JFrame f;
ComboBoxExample1(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
2
MADHAVI
6
Java Swing

public void actionPerformed(ActionEvent e) {


String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample1();
}
}
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, Object[] Creates a table with the specified
columns) data.
Java JTable Example
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);
2
MADHAVI
7
Java Swing

JScrollPane sp=new JScrollPane(jt);


f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output:

Java JTable Example with ListSelectionListener


import javax.swing.*;
import javax.swing.event.*;
public class TableExample1 {
public static void main(String[] a) {
JFrame f = new JFrame("Table Example");
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
final JTable jt=new JTable(data,column);
jt.setCellSelectionEnabled(true);
ListSelectionModel select= jt.getSelectionModel();
select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
select.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String Data = null;
int[] row = jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for (int i = 0; i < row.length; i++) {
for (int j = 0; j < columns.length; j++) {
Data = (String) jt.getValueAt(row[i], columns[j]);
}}

2
MADHAVI
8
Java Swing

System.out.println("Table element selected is: " + Data);


}
});
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300, 200);
f.setVisible(true);
}
}
Output:

Java 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.
JList class declaration
public class JList extends JComponent implements Scrollable, Accessible
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 It is used to add a listener to the list, to be
addListSelectionListener( notified each time a change to the
selection occurs.

2
MADHAVI
9
Java Swing

ListSelectionListener
listener)
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[] It is used to create a read-only ListModel
listData) from an array of objects.
Java JList 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:

Java JList Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class ListExample1

3
MADHAVI
0
Java Swing

{
ListExample1(){
JFrame f= new JFrame();
final JLabel label = new JLabel();
label.setSize(500,100);
JButton b=new JButton("Show");
b.setBounds(200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
final JList<String> list1 = new JList<>(l1);
list1.setBounds(100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
l2.addElement("Turbo C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
final JList<String> list2 = new JList<>(l2);
list2.setBounds(100,200, 75,75);
f.add(list1); f.add(list2); f.add(b); f.add(label);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if (list1.getSelectedIndex() != -1) {
data = "Programming language Selected: " +
list1.getSelectedValue();
label.setText(data);
}
if(list2.getSelectedIndex() != -1){
data += ", FrameWork Selected: ";
for(Object frame :list2.getSelectedValues()){
data += frame + " ";
}
}
3
MADHAVI
1
Java Swing

label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample1();
}}
Output:

Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as
message dialog box, confirm dialog box and input dialog box. These
dialog boxes are used to display information or get input from the user.
The JOptionPane class inherits JComponent class.
JOptionPane class declaration
public class JOptionPane extends JComponent implements Accessible
Common Constructors of JOptionPane class
Constructor Description
JOptionPane() It is used to create a JOptionPane
with a test message.
JOptionPane(Object message) It is used to create an instance of
JOptionPane to display a
message.
JOptionPane(Object message, int It is used to create an instance of
messageType) JOptionPane to display a message

3
MADHAVI
2
Java Swing

with specified message type and


default options.
Common Methods of JOptionPane class
Methods Description
JDialog createDialog(String title) It is used to create and return a
new parentless JDialog with the
specified title.
static void It is used to create an
showMessageDialog(Component information-message dialog
parentComponent, Object message) titled "Message".
static void It is used to create a message
showMessageDialog(Component dialog with given title and
parentComponent, Object message, messageType.
String title, int messageType)
static int It is used to create a dialog with
showConfirmDialog(Component the options Yes, No and Cancel;
parentComponent, Object message) with the title, Select an Option.
static String It is used to show a question-
showInputDialog(Component message dialog requesting input
parentComponent, Object message) from the user parented to
parentComponent.
void setInputValue(Object It is used to set the input value
newValue) that was selected or input by the
user.
Java JOptionPane Example: showMessageDialog()
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to
ITTEAMWORK."); }
public static void main(String[] args) {
new OptionPaneExample();
} }
Output:

3
MADHAVI
3
Java Swing

Java JOptionPane Example: showMessageDialog()


import javax.swing.*;
public class OptionPaneExample1 {
JFrame f;
OptionPaneExample1(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully
Updated.","Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample1();
}
}
Output:

Java JOptionPane Example: showInputDialog()


import javax.swing.*;
public class OptionPaneExample2 {
JFrame f;
OptionPaneExample2(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample2();
}
}
Output:

3
MADHAVI
4
Java Swing

Java JOptionPane Example: showConfirmDialog()


import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample4 extends WindowAdapter{
JFrame f;
OptionPaneExample4(){
f=new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample4();
}
}
Output:

Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical
scrollbar. It is an implementation of a scrollbar. It inherits JComponent
class.
JScrollBar class declaration
public class JScrollBar extends JComponent implements Adjustable,
Accessible

3
MADHAVI
5
Java Swing

Commonly used Constructors:


Constructor Description
JScrollBar() Creates a vertical scrollbar with
the initial values.
JScrollBar(int orientation) Creates a scrollbar with the
specified orientation and the initial
values.
JScrollBar(int orientation, int Creates a scrollbar with the
value, int extent, int min, int max) specified orientation, value,
extent, minimum, and maximum.
Java JScrollBar Example
import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}
Output:

3
MADHAVI
6
Java Swing

Java JScrollBar Example with AdjustmentListener


import javax.swing.*;
import java.awt.event.*;
class ScrollBarExample1
{
ScrollBarExample1(){
JFrame f= new JFrame("Scrollbar Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
final JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}
public static void main(String args[])
{
new ScrollBarExample1();
}}
Output:

3
MADHAVI
7
Java Swing

Java 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.
JMenuBar class declaration
public class JMenuBar extends JComponent implements MenuElement,
Accessible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement,
Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible,
MenuElement
Java 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);
3
MADHAVI
8
Java Swing

f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:

Example of creating Edit menu for Notepad:


import javax.swing.*;
import java.awt.event.*;
public class MenuExample1 implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample1(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
3
MADHAVI
9
Java Swing

edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample1();
}
}
Output:

Java JPopupMenu
PopupMenu can be dynamically popped up at specific position within a
component. It inherits the JComponent class.
JPopupMenu class declaration
public class JPopupMenu extends JComponent implements Accessible,
MenuElement

4
MADHAVI
0
Java Swing

Commonly used Constructors:


Constructor Description
JPopupMenu() Constructs a JPopupMenu without an
"invoker".
JPopupMenu(String label) Constructs a JPopupMenu with the
specified title.
Java JPopupMenu Example
import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final JFrame f= new JFrame("PopupMenu Example");
final JPopupMenu popupmenu = new JPopupMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popupmenu.add(cut); popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
} });
f.add(popupmenu);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}}
Output:

4
MADHAVI
1
Java Swing

Java JPopupMenu Example with MouseListener and ActionListener


import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample1
{
PopupMenuExample1(){
final JFrame f= new JFrame("PopupMenu Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
final JPopupMenu popupmenu = new JPopupMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popupmenu.add(cut); popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
cut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setText("cut MenuItem clicked.");
}
});
copy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setText("copy MenuItem clicked.");
}
});
paste.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setText("paste MenuItem clicked.");
}
});
f.add(label); f.add(popupmenu);
f.setSize(400,400);
f.setLayout(null);
4
MADHAVI
2
Java Swing

f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample1();
}
}
Output:

Java JCheckBoxMenuItem
JCheckBoxMenuItem class represents checkbox which can be included
on a menu. A CheckBoxMenuItem can have text or a graphic icon or
both, associated with it. MenuItem can be selected or deselected.
MenuItems can be configured and controlled by actions.
Nested class
Modifier Class Description
and Type
protected JCheckBoxMenuItem.AccessibleJ This class
class CheckBoxMenuItem implements
accessibility support
for the
JcheckBoxMenuIte
m class.
Constructor
Constructor Description
JCheckBoxMenuItem() It creates an initially unselected
check box menu item with no set
text or icon.
JCheckBoxMenuItem(Action a) It creates a menu item whose
properties are taken from the
Action supplied.

4
MADHAVI
3
Java Swing

JCheckBoxMenuItem(Icon icon) It creates an initially unselected


check box menu item with an
icon.
JCheckBoxMenuItem(String text) It creates an initially unselected
check box menu item with text.
JCheckBoxMenuItem(String text, It creates a check box menu item
boolean b) with the specified text and
selection state.
JCheckBoxMenuItem(String text, It creates an initially unselected
Icon icon) check box menu item with the
specified text and icon.
JCheckBoxMenuItem(String text, It creates a check box menu item
Icon icon, boolean b) with the specified text, icon, and
selection state.
Methods
Modifier Method Description
AccessibleContext getAccessibleContext() It gets the
AccessibleContext
associated with this
JCheckBoxMenuItem.
Object[] getSelectedObjects() It returns an array
(length 1) containing
the check box menu
item label or null if the
check box is not
selected.
boolean getState() It returns the selected-
state of the item.
String.
String getUIClassID() It returns the name of
the L&F class that
renders this
component.
protected String paramString() It returns a string
representation of this
JCheckBoxMenuItem.
void setState(boolean b) It sets the selected-
state of the item.

4
MADHAVI
4
Java Swing

Java JCheckBoxMenuItem Example


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JavaCheckBoxMenuItem {
public static void main(final String args[]) {
JFrame frame = new JFrame("Jmenu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
// File Menu, F - Mnemonic
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
// File->New, N - Mnemonic
JMenuItem menuItem1 = new JMenuItem("Open",
KeyEvent.VK_N);
fileMenu.add(menuItem1);
JCheckBoxMenuItem caseMenuItem = new
JCheckBoxMenuItem("Option_1");
caseMenuItem.setMnemonic(KeyEvent.VK_C);
fileMenu.add(caseMenuItem);
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
AbstractButton aButton = (AbstractButton) event.getSource();
boolean selected = aButton.getModel().isSelected();
String newLabel;
Icon newIcon;
if (selected) {
newLabel = "Value-1";
} else {
newLabel = "Value-2";
4
MADHAVI
5
Java Swing

}
aButton.setText(newLabel);
}
};
caseMenuItem.addActionListener(aListener);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
Output:

Java JSeparator
The object of JSeparator class is used to provide a general purpose
component for implementing divider lines. It is used to draw a line to
separate widgets in a Layout. It inherits JComponent class.
JSeparator class declaration
public class JSeparator extends JComponent implements
SwingConstants, Accessible
Commonly used Constructors of JSeparator
Constructor Description
JSeparator() Creates a new horizontal separator.
JSeparator(int orientation) Creates a new separator with the
specified horizontal or vertical
orientation.
Commonly used Methods of JSeparator
Method Description
void setOrientation(int orientation) It is used to set the orientation of
the separator.
int getOrientation() It is used to return the orientation
of the separator.
Java JSeparator Example 1
import javax.swing.*;
class SeparatorExample
{
4
MADHAVI
6
Java Swing

JMenu menu, submenu;


JMenuItem i1, i2, i3, i4, i5;
SeparatorExample() {
JFrame f= new JFrame("Separator Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
menu.add(i1);
menu.addSeparator();
menu.add(i2);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new SeparatorExample();
}}
Output:

Java JSeparator Example 2


import javax.swing.*;
import java.awt.*;
public class SeparatorExample1
{
public static void main(String args[]) {
JFrame f = new JFrame("Separator Example");
f.setLayout(new GridLayout(0, 1));
JLabel l1 = new JLabel("Above Separator");
f.add(l1);
JSeparator sep = new JSeparator();

4
MADHAVI
7
Java Swing

f.add(sep);
JLabel l2 = new JLabel("Below Separator");
f.add(l2);
f.setSize(400, 100);
f.setVisible(true);
}
}
Output:

Java JProgressBar
The JProgressBar class is used to display the progress of the task. It
inherits JComponent class.
JProgressBar class declaration
public class JProgressBar extends JComponent implements
SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JProgressBar() It is used to create a horizontal
progress bar but no string text.
JProgressBar(int min, int max) It is used to create a horizontal
progress bar with the specified
minimum and maximum value.
JProgressBar(int orient) It is used to create a progress bar
with the specified orientation, it can
be either Vertical or Horizontal by
using SwingConstants.VERTICAL
and
SwingConstants.HORIZONTAL
constants.
JProgressBar(int orient, int min, It is used to create a progress bar
int max) with the specified orientation,
minimum and maximum value.

4
MADHAVI
8
Java Swing

Commonly used Methods:


Method Description
void setStringPainted(boolean b) It is used to determine whether
string should be displayed.
void setString(String s) It is used to set value to the progress
string.
void setOrientation(int It is used to set the orientation, it
orientation) may be either vertical or horizontal
by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL
constants.
void setValue(int value) It is used to set the current value on
the progress bar.
Java JProgressBar Example
import javax.swing.*;
public class ProgressBarExample extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
ProgressBarExample m=new ProgressBarExample();
m.setVisible(true);
m.iterate();
} }
4
MADHAVI
9
Java Swing

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.
JTree class declaration
public class JTree extends JComponent implements Scrollable,
Accessible
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 {
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");
5
MADHAVI
0
Java Swing

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 JColorChooser
The JColorChooser class is used to create a color chooser dialog box so
that user can select any color. It inherits JComponent
class.
JColorChooser class declaration
public class JColorChooser extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JColorChooser() It is used to create a color chooser
panel with white color initially.
JColorChooser(color initialcolor) It is used to create a color chooser
panel with the specified color
initially.
Commonly used Methods:
Method Description
void It is used to add a color
addChooserPanel(AbstractColorChooserPanel chooser panel to the
panel) color chooser.

5
MADHAVI
1
Java Swing

static Color showDialog(Component c, String It is used to show the


title, Color initialColor) color chooser dialog
box.
Java JColorChooser Example
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ColorChooserExample extends JFrame implements
ActionListener {
JButton b;
Container c;
ColorChooserExample(){
c=getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("color");
b.addActionListener(this);
c.add(b); }
public void actionPerformed(ActionEvent e) {
Color initialcolor=Color.RED;
Color color=JColorChooser.showDialog(this,"Select a
color",initialcolor);
c.setBackground(color); }
public static void main(String[] args) {
ColorChooserExample ch=new ColorChooserExample();
ch.setSize(400,400);
ch.setVisible(true);
ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
} }
Output:

5
MADHAVI
2
Java Swing

Java JColorChooser Example with ActionListener


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample1 extends JFrame implements
ActionListener{
JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample1(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
ta=new JTextArea();
ta.setBounds(10,10,300,200);
b.addActionListener(this);
f.add(b);f.add(ta);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true); }
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
ta.setBackground(c); }
public static void main(String[] args) {
new ColorChooserExample1();
} }
Output:

5
MADHAVI
3
Java Swing

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
public class JTabbedPane extends JComponent implements Serializable,
Accessible, SwingConstants
Commonly used Constructors:
Constructor Description
JTabbedPane() Creates an empty TabbedPane
with a default tab placement of
JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane
with a specified tab placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane
tabLayoutPolicy) with a specified tab placement and
tab layout policy.
Java JTabbedPane Example
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
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) {

5
MADHAVI
4
Java Swing

new TabbedPaneExample();
}}
Output:

Java JSlider
The Java JSlider class is used to create the slider. By using JSlider, a user
can select a value from a specific range.
Commonly used Constructors of JSlider class
Constructor Description
JSlider() creates a slider with the initial
value of 50 and range of 0 to 100.
JSlider(int orientation) creates a slider with the specified
orientation set by either
JSlider.HORIZONTAL or
JSlider.VERTICAL with the range
0 to 100 and initial value 50.
JSlider(int min, int max) creates a horizontal slider using the
given min and max.
JSlider(int min, int max, int creates a horizontal slider using the
value) given min, max and value.
JSlider(int orientation, int min, int creates a slider using the given
max, int value) orientation, min, max and value.
Commonly used Methods of JSlider class
Method Description
public void is used to set the minor tick
setMinorTickSpacing(int n) spacing to the slider.
public void is used to set the major tick
setMajorTickSpacing(int n) spacing to the slider.
public void setPaintTicks(boolean is used to determine whether tick
b) marks are painted.
public void setPaintLabels(boolean is used to determine whether
b) labels are painted.
public void setPaintTracks(boolean is used to determine whether
b) track is painted.
5
MADHAVI
5
Java Swing

Java JSlider Example


import javax.swing.*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
SliderExample1 frame=new SliderExample1();
frame.pack();
frame.setVisible(true);
}
}
Output:

Java JSlider Example: painting ticks


import javax.swing.*;
public class SliderExample extends JFrame{
public SliderExample() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
SliderExample frame=new SliderExample();
frame.pack();
frame.setVisible(true);
}
}

5
MADHAVI
6
Java Swing

Output:

Java JSpinner
The object of JSpinner class is a single line input field that allows the user
to select a number or an object value from an ordered sequence.
JSpinner class declaration
public class JSpinner extends JComponent implements Accessible
Commonly used Contructors:
Constructor Description
JSpinner() It is used to construct a spinner
with an Integer
SpinnerNumberModel with initial
value 0 and no minimum or
maximum limits.
JSpinner(SpinnerModel model) It is used to construct a spinner for
a given model.
Commonly used Methods:
Method Description
void It is used to add a listener to the
addChangeListener(ChangeListener list that is notified each time a
listener) change to the model occurs.
Object getValue() It is used to return the current
value of the model.
Java JSpinner Example
import javax.swing.*;
public class SpinnerExample {
public static void main(String[] args) {
JFrame f=new JFrame("Spinner Example");
SpinnerModel value =
new SpinnerNumberModel(5, //initial value
0, //minimum value
10, //maximum value
1); //step
JSpinner spinner = new JSpinner(value);
spinner.setBounds(100,100,50,30);
f.add(spinner);
f.setSize(300,300);
5
MADHAVI
7
Java Swing

f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java JSpinner Example with ChangeListener


import javax.swing.*;
import javax.swing.event.*;
public class SpinnerExample1 {
public static void main(String[] args) {
JFrame f=new JFrame("Spinner Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(250,100);
SpinnerModel value =
new SpinnerNumberModel(5, //initial value
0, //minimum value
10, //maximum value
1); //step
JSpinner spinner = new JSpinner(value);
spinner.setBounds(100,100,50,30);
f.add(spinner); f.add(label);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
label.setText("Value : " + ((JSpinner)e.getSource()).getValue());
}
});
} }

5
MADHAVI
8
Java Swing

Output:

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.
JDialog class declaration
public class JDialog extends Dialog implements WindowConstants,
Accessible, RootPaneContainer
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
boolean modal) the specified title, owner Frame
and modality.
Java JDialog 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");
5
MADHAVI
9
Java Swing

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 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.
JPanel class declaration
public class JPanel extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JPanel() It is used to create a new JPanel
with a double buffer and a flow
layout.
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel
with FlowLayout and the
specified buffering strategy.

6
MADHAVI
0
Java Swing

JPanel(LayoutManager layout) It is used to create a new JPanel


with the specified layout
manager.
Java JPanel Example
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:

6
MADHAVI
1
Java Swing

Java JFileChooser
The object of JFileChooser class represents a dialog window from which
the user can select file. It inherits JComponent class.
JFileChooser class declaration
public class JFileChooser extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JFileChooser() Constructs a JFileChooser pointing to the
user's default directory.
JFileChooser(File Constructs a JFileChooser using the given
currentDirectory) File as the path.
JFileChooser(String Constructs a JFileChooser using the given
currentDirectoryPath) path.
Java JFileChooser Example
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements
ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();

6
MADHAVI
2
Java Swing

int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
}
}
}
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to
switch on or off.
Nested Classes
Modifier Class Description
and Type
protected JToggleButton.AccessibleJToggleButton This class
class implements
accessibility
support for the
6
MADHAVI
3
Java Swing

JToggleButton
class.
static class JToggleButton.ToggleButtonModel The
ToggleButton
model
Constructors
Constructor Description
JToggleButton() It creates an initially unselected
toggle button without setting the
text or image.
JToggleButton(Action a) It creates a toggle button where
properties are taken from the
Action supplied.
JToggleButton(Icon icon) It creates an initially unselected
toggle button with the specified
image but no text.
JToggleButton(Icon icon, boolean It creates a toggle button with the
selected) specified image and selection
state, but no text.
JToggleButton(String text) It creates an unselected toggle
button with the specified text.
JToggleButton(String text, boolean It creates a toggle button with the
selected) specified text and selection state.
JToggleButton(String text, Icon It creates a toggle button that has
icon) the specified text and image, and
that is initially unselected.
JToggleButton(String text, Icon It creates a toggle button with the
icon, boolean selected) specified text, image, and
selection state.
Methods

Modifier and Type Method Description


AccessibleContext It gets the AccessibleContext
getAccessibleContext() associated 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.

6
MADHAVI
4
Java Swing

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


from the current look and feel.
JToggleButton 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");
}
}

6
MADHAVI
5
Java Swing

Output

Java JToolBar
JToolBar container allows us to group other components, usually buttons
with icons in a row or column. JToolBar provides a component which is
useful for displaying commonly used actions or controls.
Nested Classes
Modifier and Class Description
Type
protected class JToolBar.AccessibleJToolBar This class
implements
accessibility
support for the
JToolBar class.
static class JToolBar.Separator A toolbar-specific
separator.
Constructors
Constructor Description
JToolBar() It creates a new tool bar;
orientation defaults to
HORIZONTAL.
JToolBar(int orientation) It creates a new tool bar with the
specified orientation.
JToolBar(String name) It creates a new tool bar with the
specified name.
JToolBar(String name, int It creates a new tool bar with a
orientation) specified name and orientation.
Useful Methods
Modifier and Type Method Description
JButton add(Action a) It adds a new JButton
which dispatches the
action.
protected void addImpl(Compone If a JButton is being added,
nt comp, Object it is initially set to be
constraints, int disabled.
index)

6
MADHAVI
6
Java Swing

void addSeparator() It appends a separator of


default size to the end of
the tool bar.
protected createActionChang It returns a properly
PropertyChangeList eListener(JButton configured
ener b) PropertyChangeListener
which updates the control
as changes to the Action
occur, or null if the default
property change listener for
the control is desired.
protected JButton createActionComp Factory method which
onent(Action a) creates the JButton for
Actions added to the
JToolBar.
ToolBarUI getUI() It returns the tool bar's
current UI.
void setUI(ToolBarUI It sets the L&F object that
ui) renders this component.
void setOrientation(int It sets the orientation of the
o) tool bar.
Java JToolBar Example
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
public class JToolBarExample {
public static void main(final String args[]) {
JFrame myframe = new JFrame("JToolBar Example");
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToolBar toolbar = new JToolBar();
toolbar.setRollover(true);
JButton button = new JButton("File");
toolbar.add(button);
toolbar.addSeparator();
toolbar.add(new JButton("Edit"));

6
MADHAVI
7
Java Swing

toolbar.add(new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-


3", "Opt-4" }));
Container contentPane = myframe.getContentPane();
contentPane.add(toolbar, BorderLayout.NORTH);
JTextArea textArea = new JTextArea();
JScrollPane mypane = new JScrollPane(textArea);
contentPane.add(mypane, BorderLayout.EAST);
myframe.setSize(450, 250);
myframe.setVisible(true);
}
}
Output:

Java JViewport
The JViewport class is used to implement scrolling. JViewport is
designed to support both logical scrolling and pixel-based scrolling. The
viewport's child, called the view, is scrolled by calling the
JViewport.setViewPosition() method.
Nested Classes
Modifier and Class Description
Type
protected class JViewport.AccessibleJViewport This class
implements
accessibility
support for the
Jviewport class.
protected class JViewport.ViewListener A listener for the
view.

6
MADHAVI
8
Java Swing

Fields
Modifier Field Description
and Type
static int BACKINGSTORE_SCROLL_MODE It draws viewport
contents into an
offscreen image.
protected backingStoreImage The view image
Image used for a backing
store.
static int BLIT_SCROLL_MODE It uses
graphics.copyArea
to implement
scrolling.
protected isViewSizeSet True when the
boolean viewport
dimensions have
been determined.
protected lastPaintPosition The last
Point viewPosition that
we've painted, so
we know how
much of the
backing store
image is valid.
protected scrollUnderway The
boolean scrollUnderway
flag is used for
components like
JList.
static int SIMPLE_SCROLL_MODE This mode uses
the very simple
method of
redrawing the
entire contents of
the scrollpane each
time it is scrolled.

6
MADHAVI
9
Java Swing

Constructor
Constructor Description
JViewport() Creates a JViewport.
Methods
Modifier and Type Method Description
void addChangeListener(ChangeList It adds a
ener l) ChangeListen
er to the list
that is
notified each
time the
view's size,
position, or
the viewport's
extent size
has changed.
protected createLayoutManager() Subclassers
LayoutManager can override
this to install
a different
layout
manager (or
null) in the
constructor.
protected createViewListener() It creates a
Jviewport.ViewListe listener for
ner the view.
int getScrollMode() It returns the
current
scrolling
mode.
Component getView() It returns the
JViewport's
one child or
null.
Point getViewPosition() It returns the
view
coordinates
that appear in
the upper left
hand corner

7
MADHAVI
0
Java Swing

of the
viewport, or
0,0 if there's
no view.
Dimension getViewSize() If the view's
size hasn't
been
explicitly set,
return the
preferred
size,
otherwise
return the
view's current
size.
void setExtentSize(Dimension It sets the size
newExtent) of the visible
part of the
view using
view
coordinates.
void setScrollMode(int mode) It used to
control the
method of
scrolling the
viewport
contents.
void setViewSize(Dimension It sets the size
newSize) of the view.
JViewport Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
public class ViewPortClass2 {
public static void main(String[] args) {
JFrame frame = new JFrame("Tabbed Pane Sample");
7
MADHAVI
1
Java Swing

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton jButton1 = new JButton();
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_S
CROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
jScrollPane.getViewport().add(jButton1, null);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
Output:

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.
Modifier and Type Class Description
protected class JFrame.AccessibleJFrame This class
implements
accessibility support
for the JFrame class.

7
MADHAVI
2
Java Swing

Fields
Modifier and Type Field Description
protected accessibleContext The accessible
AccessibleContext context property.
static int EXIT_ON_CLOSE The exit
application default
window close
operation.
protected JRootPane rootPane The JRootPane
instance that
manages the
contentPane and
optional menuBar
for this frame, as
well as the
glassPane.
protected boolean rootPaneCheckingEnabled If true then calls to
add and setLayout
will be forwarded
to the contentPane.
Constructors
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
GraphicsConfiguration gc) specified title and the specified
GraphicsConfiguration of a
screen device.
Useful Methods
Modifier Method Description
and Type
protected addImpl(Component comp, Object Adds the specified
void constraints, int index) child Component.
protected createRootPane() Called by the
JRootPane constructor methods

7
MADHAVI
3
Java Swing

to create the default


rootPane.
protected frameInit() Called by the
void constructors to init
the JFrame
properly.
void setContentPane(Containe It sets the
contentPane) contentPane
property
static void setDefaultLookAndFeelDecorated( Provides a hint as to
boolean whether or not
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) layeredPane
property.
JRootPane getRootPane() It returns the
rootPane object for
this frame.
TransferHa getTransferHandler() It gets the
ndler transferHandler
property.
JFrame Example
import java.awt.*;
import javax.swing.*;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");

7
MADHAVI
4
Java Swing

JPanel panel = new JPanel();


panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output

Java JLayeredPane
The JLayeredPane class is used to add depth to swing container. It is used
to provide a third dimension for positioning component and divide the
depth-range into several different layers.
JLayeredPane class declaration
public class JLayeredPane extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JLayeredPane It is used to create a new
JLayeredPane
Commonly used Methods:
Method Description
int getIndexOf(Component c) It is used to return the index of the
specified Component.
int getLayer(Component c) It is used to return the layer attribute
for the specified Component.
int getPosition(Component c) It is used to return the relative
position of the component within its
layer.

7
MADHAVI
5
Java Swing

Java JLayeredPane Example


import javax.swing.*;
import java.awt.*;
public class LayeredPaneExample extends JFrame {
public LayeredPaneExample() {
super("LayeredPane Example");
setSize(200, 200);
JLayeredPane pane = getLayeredPane();
//creating buttons
JButton top = new JButton();
top.setBackground(Color.white);
top.setBounds(20, 20, 50, 50);
JButton middle = new JButton();
middle.setBackground(Color.red);
middle.setBounds(40, 40, 50, 50);
JButton bottom = new JButton();
bottom.setBackground(Color.cyan);
bottom.setBounds(60, 60, 50, 50);
//adding buttons on pane
pane.add(bottom, new Integer(1));
pane.add(middle, new Integer(2));
pane.add(top, new Integer(3));
}
public static void main(String[] args) {
LayeredPaneExample panel = new LayeredPaneExample();
panel.setVisible(true);
}
}
Output:

7
MADHAVI
6
Java Swing

Java JDesktopPane
The JDesktopPane class, can be used to create "multi-document"
applications. A multi-document application can have many windows
included in it. We do it by making the contentPane in the main window as
an instance of the JDesktopPane class or a subclass. Internal windows add
instances of JInternalFrame to the JdesktopPane instance. The internal
windows are the instances of JInternalFrame or its subclasses.
Fields
Modifier and Type Field Description
static int LIVE_DRAG_MODE It indicates that the
entire contents of
the item being
dragged should
appear inside the
desktop pane.
static int OUTLINE_DRAG_MODE It indicates that an
outline only of the
item being dragged
should appear inside
the desktop pane.
Constructor
Constructor Description
JDesktopPane() Creates a new JDesktopPane.
Java JDesktopPane Example
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
public class JDPaneDemo extends JFrame
{
public JDPaneDemo()
{
CustomDesktopPane desktopPane = new CustomDesktopPane();
Container contentPane = getContentPane();
contentPane.add(desktopPane, BorderLayout.CENTER);
desktopPane.display(desktopPane);
setTitle("JDesktopPane Example");
setSize(300,350);
7
MADHAVI
7
Java Swing

setVisible(true);
}
public static void main(String args[])
{
new JDPaneDemo();
}
}
class CustomDesktopPane extends JDesktopPane
{
int numFrames = 3, x = 30, y = 30;
public void display(CustomDesktopPane dp)
{
for(int i = 0; i < numFrames ; ++i )
{
JInternalFrame jframe = new JInternalFrame("Internal Frame " + i ,
true, true, true, true);
jframe.setBounds(x, y, 250, 85);
Container c1 = jframe.getContentPane( ) ;
c1.add(new JLabel("I love my country"));
dp.add( jframe );
jframe.setVisible(true);
y += 85;
}
}
}
Output:

7
MADHAVI
8
Java Swing

Java JEditorPane
JEditorPane class is used to create a simple text editor window. This class
has setContentType() and setText() methods.
setContentType("text/plain"): This method is used to set the content type
to be plain text.
setText(text): This method is used to set the initial text content.
Nested Classes
Modi Class Description
fier
and
Type
prote JEditorPane.AccessibleJEditorP This class implements
cted ane accessibility support for the
class JEditorPane class.
prote JEditorPane.AccessibleJEditorP This class provides support
cted aneHTML for AccessibleHypertext, and
class is used in instances where the
EditorKit installed in this
JEditorPane is an instance of
HTMLEditorKit.
prote JEditorPane.JEditorPaneAccessi What's returned by
cted bleHypertextSupport AccessibleJEditorPaneHTM
class L.getAccessibleText
Fields
Modifier and Field Description
Type
static String HONOR_DISPLAY_PRO Key for a client property
PERTIES used to indicate whether
the default font and
foreground color from
the component are used
if a font or foreground
color is not specified in
the styled text.
static String W3C_LENGTH_UNITS Key for a client property
used to indicate whether
w3c compliant length
units are used for html
rendering.

7
MADHAVI
9
Java Swing

Constructors
Constructor Description
JEditorPane() It creates a new JEditorPane.
JEditorPane(String url) It creates a JEditorPane based on
a string containing a URL
specification.
JEditorPane(String type, String It creates a JEditorPane that has
text) been initialized to the given text.
JEditorPane(URL initialPage) It creates a JEditorPane based on
a specified URL for input.
Useful Methods
Modifier Method Description
and Type
void addHyperlinkListener(Hyp Adds a hyperlink listener for
erlinkListener listener) notification of any changes,
for example when a link is
selected and entered.
protected createDefaultEditorKit() It creates the default editor kit
EditorKit (PlainEditorKit) for when the
component is first created.
void setText(String t) It sets the text of this
TextComponent to the
specified content, which is
expected to be in the format
of the content type of this
editor.
void setContentType(String It sets the type of content that
type) this editor handles.
void setPage(URL page) It sets the current URL being
displayed.
void read(InputStream in, This method initializes from a
Object desc) stream.
void scrollToReference(String It scrolls the view to the given
reference) reference location (that is, the
value returned by the
UL.getRef method for the
URL being displayed).
void setText(String t) It sets the text of this
TextComponent to the
specified content, which is
expected to be in the format

8
MADHAVI
0
Java Swing

of the content type of this


editor.
String getText() It returns the text contained in
this TextComponent in terms
of the content type of this
editor.
void read(InputStream in, This method initializes from a
Object desc) stream.
JEditorPane Example
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class JEditorPaneExample {
JFrame myFrame = null;
public static void main(String[] a) {
(new JEditorPaneExample()).test();
}
private void test() {
myFrame = new JFrame("JEditorPane Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400, 200);
JEditorPane myPane = new JEditorPane();
myPane.setContentType("text/plain");
myPane.setText("Sleeping is necessary for a healthy body."
+ " But sleeping in unnecessary times may spoil our health,
wealth and studies."
+ " Doctors advise that the sleeping at improper timings may
lead for obesity during the students days.");
myFrame.setContentPane(myPane);
myFrame.setVisible(true);
}
}
Output:

8
MADHAVI
1
Java Swing

JEditorPane Example: using HTML


import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class JEditorPaneExample1 {
JFrame myFrame = null;
public static void main(String[] a) {
(new JEditorPaneExample1()).test();
}
private void test() {
myFrame = new JFrame("JEditorPane Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400, 200);
JEditorPane myPane = new JEditorPane();
myPane.setContentType("text/html");
myPane.setText("<h1>Sleeping</h1><p>Sleeping is necessary for a
healthy body."
+ " But sleeping in unnecessary times may spoil our health,
wealth and studies."
+ " Doctors advise that the sleeping at improper timings may
lead for obesity during the students days.</p>");
myFrame.setContentPane(myPane);
myFrame.setVisible(true);
}
}
Output:

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.

8
MADHAVI
2
Java Swing

Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The
JScrollPane(Component) Component parameter, when
JScrollPane(int, int) present, sets the scroll pane's
JScrollPane(Component, int, int) client. The two int parameters,
when present, set the vertical and
horizontal scroll bar policies
(respectively).
Useful Methods
Modifier Method Description
void setColumnHeaderView(C It sets the column header for
omponent) the scroll pane.
void setRowHeaderView(Com It sets the row header for the
ponent) scroll pane.
void setCorner(String, It sets or gets the specified
Component) corner. The int parameter
Compon getCorner(String) specifies which corner and
ent must be one of the following
constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNE
R,
LOWER_TRAILING_CORNE
R,
UPPER_LEADING_CORNER
,
UPPER_TRAILING_CORNE
R.
void setViewportView(Compo Set the scroll pane's client.
nent)
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.*;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
8
MADHAVI
3
Java Swing

// 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.HORIZON
TAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_
SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Output:

8
MADHAVI
4
Java Swing

Java 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.
Constructors
Constructor Description
JSplitPane() It creates a new JsplitPane
configured to arrange the child
components side-by-side
horizontally, using two buttons
for the components.
JSplitPane(int newOrientation) It creates a new JsplitPane
configured with the specified
orientation.
JSplitPane(int newOrientation, It creates a new JsplitPane with
boolean newContinuousLayout) the specified orientation and
redrawing style.
JSplitPane(int newOrientation, It creates a new JsplitPane with
boolean newContinuousLayout, the specified orientation and
Component newLeftComponent, redrawing style, and with the
Component newRightComponent) specified components.
JSplitPane(int newOrientation, It creates a new JsplitPane with
Component newLeftComponent, the specified orientation and the
Component newRightComponent) specified components.
Useful Methods
Modifier and Type Method Description
protected void addImpl(Component It cdds the specified
comp, Object constraints, component to this split
int index) pane.
AccessibleContext It gets the
getAccessibleCont AccessibleContext
ext() associated with this
JSplitPane.

8
MADHAVI
5
Java Swing

int getDividerLocation() It returns the last value


passed to
setDividerLocation.
int getDividerSize() It returns the size of
the divider.
Component getBottomComponent() It returns the
component below, or
to the right of the
divider.
Component getRightComponent() It returns the
component to the right
(or below) the divider.
SplitPaneUI getUI() It returns the
SplitPaneUI that is
providing the current
look and feel.
boolean isContinuousLayout() It gets the
continuousLayout
property.
boolean isOneTouchExpandable() It gets the
oneTouchExpandable
property.
void setOrientation(int It gets the orientation,
orientation) or how the splitter is
divided.
JSplitPane Example
import java.awt.FlowLayout;
import java.awt.Panel;
import javax.swing.*;
public class JSplitPaneExample {
private static void createAndShow() {
// Create and set up the window.
final JFrame frame = new JFrame("JSplitPane Example");
// Display the window.
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
String[] option1 = { "A","B","C","D","E" };

8
MADHAVI
6
Java Swing

JComboBox box1 = new JComboBox(option1);


String[] option2 = {"1","2","3","4","5"};
JComboBox box2 = new JComboBox(option2);
Panel panel1 = new Panel();
panel1.add(box1);
Panel panel2 = new Panel();
panel2.add(box2);
JSplitPane splitPane = new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
// JSplitPane splitPane = new
JSplitPane(JSplitPane.VERTICAL_SPLIT,
// panel1, panel2);
frame.getContentPane().add(splitPane);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShow();
}
});
}
}
Output:

Java JTextPane
JTextPane is a subclass of JEditorPane class. JTextPane is used for styled
document with embedded images and components. It is text component
that can be marked up with attributes that are represented graphically.
JTextPane uses a DefaultStyledDocument as its default model.

8
MADHAVI
7
Java Swing

Constructors
Constructor Description
JTextPane() It creates a new JTextPane.
JtextPane(StyledDocument doc) It creates a new JTextPane, with
a specified document model.
Useful Methods
Modifier and Type Method Description
Style addStyle(String nm, Style It adds a new style into the
parent) logical style hierarchy.
AttributeSet getCharacterAttributes() It fetches the character
attributes in effect at the
current location of the caret, or
null.
StyledDocument It fetches the model associated
getStyledDocument() with the editor.
void setDocument(Document doc) It associates the editor with a
text document.
void It applies the given attributes
setCharacterAttributes(Attribute to character content.
Set attr, boolean replace)
void removeStyle(String nm) It removes a named non-null
style previously added to the
document.
void setEditorKit(EditorKit kit) It sets the currently installed
kit for handling content.
void It associates the editor
setStyledDocument(StyledDocu with a text document.
ment doc)
JTextPane Example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneExample {
public static void main(String args[]) throws BadLocationException {
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
JTextPane pane = new JTextPane();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setBold(attributeSet, true);

8
MADHAVI
8
Java Swing

// Set the attributes before adding text


pane.setCharacterAttributes(attributeSet, true);
pane.setText("Welcome");
attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.red);
StyleConstants.setBackground(attributeSet, Color.blue);
Document doc = pane.getStyledDocument();
doc.insertString(doc.getLength(), "To Java ", attributeSet);
attributeSet = new SimpleAttributeSet();
doc.insertString(doc.getLength(), "World", attributeSet);
JScrollPane scrollPane = new JScrollPane(pane);
cp.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
Output

Java JRootPane
JRootPane is a lightweight container used behind the scenes by JFrame,
JDialog, JWindow, JApplet, and JInternalFrame.
Constructor
Constructor Description
JRootPane() Creates a JRootPane, setting up its glassPane, layeredPane, and
contentPane.
Useful Methods
Modifier and Type Method Description
protected void Overridden to enforce the position of
addImpl(Component comp, the glass component as the zero child.
Object constraints, int index)

8
MADHAVI
9
Java Swing

void addNotify() Notifies this component that it now


has a parent component.
protected Container It is called by the constructor methods
createContentPane() to create the default contentPane.
protected Component It called by the constructor methods
createGlassPane() to create the default glassPane.
AccessibleContext It gets the AccessibleContext
getAccessibleContext() associated with this JRootPane.
JButton getDefaultButton() It returns the value of the
defaultButton property.
void setContentPane(Container It sets the content pane -- the
content) container that holds the components
parented by the root pane.
void setDefaultButton(JButton It sets the defaultButton property,
defaultButton) which determines the current default
button for this JRootPane.
void setJMenuBar(JMenuBar menu) It adds or changes the menu bar used
in the layered pane.
JRootPane Example
import javax.swing.*;
public class JRootPaneExample {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRootPane root = f.getRootPane();
// Create a menu bar
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
bar.add(menu);
menu.add("Open");
menu.add("Close");
root.setJMenuBar(bar);
// Add a button to the content pane

9
MADHAVI
0
Java Swing

root.getContentPane().add(new JButton("Press Me"));


// Display the UI
f.pack();
f.setVisible(true);
}
}
Output

How to use ToolTip in Java Swing


You can create a tool tip for any JComponent with setToolTipText() method.
This method is used to set up a tool tip for the component.
For example, to add tool tip to PasswordField, you need to add only one
line of code:
field.setToolTipText("Enter your Password");
Simple ToolTip Example
import javax.swing.*;
public class ToolTipExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
//Creating PasswordField and label
JPasswordField value = new JPasswordField();
value.setBounds(100,100,100,30);
value.setToolTipText("Enter your Password");
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
//Adding components to frame
9
MADHAVI
1
Java Swing

f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

How to change TitleBar icon in Java AWT and 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 java.awt.*;
class IconExample {
IconExample(){
Frame f=new Frame();
Image icon = Toolkit.getDefaultToolkit().getImage("a.jpg");

9
MADHAVI
2
Java Swing

f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[]){
new IconExample();
}
}
Output:

Example of digital clock in swing


import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
public class DigitalWatch implements Runnable{
JFrame f;
Thread t=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton b;
DigitalWatch(){
f=new JFrame();

9
MADHAVI
3
Java Swing

t = new Thread(this);
t.start();
b=new JButton();
b.setBounds(100,100,100,50);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
printTime();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}

9
MADHAVI
4
Java Swing

public void printTime(){


b.setText(timeString);
}
public static void main(String[] args) {
new DigitalWatch();
}
}
Output:

Displaying graphics in swing:


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
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.
public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
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.
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).

9
MADHAVI
5
Java Swing

public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
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.
public abstract void setColor(Color c): is used to set the graphics current color
to the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to
the specified font.
Example of displaying graphics in swing
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);

9
MADHAVI
6
Java Swing

f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
}
Output:

Displaying image in swing:


For displaying image, we can use the method drawImage() of Graphics class.
Syntax of drawImage() method:
public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
Example of displaying image in swing:
import java.awt.*;
import javax.swing.JFrame;
public class MyCanvas extends Canvas{
public void paint(Graphics g) {
Toolkit t=Toolkit.getDefaultToolkit();
Image i=t.getImage("a.jpg");
g.drawImage(i, 120,100,this);
9
MADHAVI
7
Java Swing

}
public static void main(String[] args) {
MyCanvas m=new MyCanvas();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
f.setVisible(true);
}
}
Output:

9
MADHAVI
8

You might also like