KEMBAR78
Java Swing | PDF | Computer Programming | Software Engineering
0% found this document useful (0 votes)
9 views171 pages

Java Swing

Java Swing is a part of Java Foundation Classes (JFC) used for creating window-based applications, built on AWT and offering platform-independent components. It provides a variety of components like JButton, JTextField, and JTable, and follows the MVC design pattern. The document also includes examples of creating GUI applications using Swing, highlighting the differences between AWT and Swing, and detailing commonly used methods and classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views171 pages

Java Swing

Java Swing is a part of Java Foundation Classes (JFC) used for creating window-based applications, built on AWT and offering platform-independent components. It provides a variety of components like JButton, JTextField, and JTable, and follows the MVC design pattern. The document also includes examples of creating GUI applications using Swing, highlighting the differences between AWT and Swing, and detailing commonly used methods and classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 171

Java Swing

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No Java AWT Java Swing


.

1) AWT components are platform- Java swing components


dependent. are platform-independent.

2) AWT components Swing components


are heavyweight. are lightweight.

3) AWT doesn't support Swing supports pluggable


pluggable look and feel. look and feel.

4) AWT provides less Swing provides more powerful


components than Swing. components such as tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC Swing follows MVC.


(Model 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.

1 | Page
Do You Know
How to create runnable jar file in java?

How to display image on a button in swing?

How to change the component color by choosing a color from ColorChooser ?

How to display the digital watch in swing tutorial ?

How to create a notepad in swing?

How to create puzzle game and pic puzzle game in swing ?

How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

2 | Page
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int sets size of the component.


height)

public void sets the layout manager for the component.


setLayout(LayoutManager m)

public void setVisible(boolean b) sets the visibility of the component. It is by


default false.

Java Swing Examples


There are two ways to create a frame:

By creating the object of Frame class (association)

By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on
the JFrame object inside the main() method.

File: FirstSwingExample.java

3 | Page
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
}
}

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the
java constructor.

File: Simple.java

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

4 | Page
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();
}
}

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example
that sets the position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.

File: Simple2.java

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

5 | Page
}}
What we will learn in Swing Tutorial
JButton class

JRadioButton class

JTextArea class

JComboBox class

JTable class

JColorChooser class

JProgressBar class

JSlider class

Digital Watch

Graphics in swing

Displaying image

Edit menu code for Notepad

OpenDialog Box

Notepad

Puzzle Game

Pic Puzzle Game

Tic Tac Toe Game

BorderLayout

GridLayout

FlowLayout
6 | Page
CardLayout

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

JButton class declaration


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

public class JButton extends AbstractButton implements Accessible

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

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

Output:

8 | Page
Java JButton Example with ActionListener
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
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:

9 | Page
Example of displaying image on the button:
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
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 ButtonExample();
}
}

Output:

Java JLabel

10 | P a g e
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.

JLabel class declaration


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

public class JLabel extends JComponent implements SwingConstants, Accessible

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() t returns the text string that a label


displays.

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


component will display.

11 | P a g e
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);
}
}

Output:

12 | P a g e
Java JLabel Example with ActionListener
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
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();

13 | P a g e
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}}

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


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

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

14 | P a g e
specified text.

JTextField(String text, int Creates a new TextField initialized with the


columns) 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 action


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

Action getAction() It returns the currently set Action for


this ActionEvent source, or null if no
Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified


removeActionListener(ActionListener action listener so that it no longer
l) 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);

15 | P a g e
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 TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
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();
16 | P a g e
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 TextFieldExample();
}}

Output:

17 | P a g e
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


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

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 Creates a text area with the specified number of
column) rows and columns that displays no text initially.

JTextArea(String s, int Creates a text area with the specified number of


row, int column) rows and columns that displays specified text.

Commonly used Methods:


18 | P a g e
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 It is used to insert the specified text on the


position) specified position.

void append(String s) It is used to append the given text to the end


of the document.

Java JTextArea Example


import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
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:

19 | P a g e
Java JTextArea Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
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);
20 | P a g e
}
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 TextAreaExample();
}
}

Output:

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.

21 | P a g e
JPasswordField class declaration
Let's see the declaration for javax.swing.JPasswordField class.

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 Constructs a new empty JPasswordField with


columns) the specified number of columns.

JPasswordField(String text) Constructs a new JPasswordField initialized


with the specified text.

JPasswordField(String text, Construct a new JPasswordField initialized with


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

22 | P a g e
Output:

Java JPasswordField Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
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);

23 | P a g e
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:

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

JCheckBox class declaration


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

public class JCheckBox extends JToggleButton implements Accessible


24 | P a g e
Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box


button with no text, no icon.

JChechBox(String s) Creates an initially unselected check box


with text.

JCheckBox(String text, Creates a check box with text and specifies


boolean selected) whether or not it is initially selected.

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


taken from the Action supplied.

Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext


getAccessibleContext() associated with this JCheckBox.

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


JCheckBox.

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

25 | P a g e
f.setLayout(null);
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 CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");

26 | P a g e
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"));
}
});
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 CheckBoxExample();
}
}

Output:

27 | P a g e
Java JCheckBox Example: Food Order
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
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);

28 | P a g e
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 CheckBoxExample();
}
}

Output:

29 | P a g e
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.

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

JRadioButton class declaration


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

public class JRadioButton extends JToggleButton implements 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.

30 | P a g e
JRadioButton(String s, boolean Creates a radio button with the specified
selected) 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.

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 listener


addActionListener(ActionListener a) 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();

31 | P a g e
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:

Java JRadioButton Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
32 | P a g e
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 RadioButtonExample();
}}

Output:

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

JComboBox class declaration


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

public class JComboBox extends JComponent implements ItemSelectable, ListData


Listener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] Creates a JComboBox that contains the elements


items) in the specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements


items) 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.

34 | P a g e
addActionListener(ActionListener
a)

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


i)

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);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

Output:

35 | P a g e
Java JComboBox Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
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() {
public void actionPerformed(ActionEvent e) {

36 | P a g e
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

Output:

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

JTable class declaration


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

Commonly used Constructors:

Constructor Description

37 | P a g e
JTable() Creates a table with empty
cells.

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


specified data.

Java JTable Example


import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"103","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}

Output:

38 | P a g e
Java JTable Example with ListSelectionListener
import javax.swing.*;
import javax.swing.event.*;
public class TableExample {
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]);
}}

39 | P a g e
System.out.println("Table element selected is: " + Data);
}
});
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300, 200);
f.setVisible(true);
}
}

Output:

If you select an element in column NAME, name of the element will be displayed on
the console:

Table element selected is: Sachin

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


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

public class JList extends JComponent implements Scrollable, Accessible

40 | P a g e
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> Creates a JList that displays elements from the


dataModel) specified, non-null, model.

Commonly used Methods:

Methods Description

Void It is used to add a listener to


addListSelectionListener(ListSelectionListen the list, to be notified each
er listener) time a change to the
selection occurs.

int getSelectedIndex() It is used to return the


smallest selected cell index.

ListModel getModel() It is used to return the data


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

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


only ListModel from an array
of objects.

Java JList Example


import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();

41 | P a g e
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 ListExample
{

42 | P a g e
ListExample(){
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 + " ";
}

43 | P a g e
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample();
}}

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


44 | P a g e
Constructor Description

JOptionPane() It is used to create a JOptionPane with a test


message.

JOptionPane(Object It is used to create an instance of


message) JOptionPane to display a message.

JOptionPane(Object It is used to create an instance of


message, int messageType JOptionPane to display a message 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 showMessageDialog(Component It is used to create an


parentComponent, Object message) information-message
dialog titled "Message".

static void showMessageDialog(Component It is used to create a


parentComponent, Object message, String message dialog with given
title, int messageType) title and messageType.

static int showConfirmDialog(Component It is used to create a dialog


parentComponent, Object message) with the options Yes, No
and Cancel; with the title,
Select an Option.

static String showInputDialog(Component It is used to show a


parentComponent, Object message) question-message dialog
requesting input from the
user parented to
parentComponent.

void setInputValue(Object newValue) It is used to set the input


value that was selected or
input by the user.

45 | P a g e
Java JOptionPane Example: showMessageDialog()
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Output:

Java JOptionPane Example: showMessageDialog()


import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNI
NG_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
46 | P a g e
}

Output:

Java JOptionPane Example: showInputDialog()


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

Output:

Java JOptionPane Example: showConfirmDialog()


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

47 | P a g e
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
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 OptionPaneExample();
}
}

Output:

Java JScrollBar
48 | P a g e
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


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

public class JScrollBar extends JComponent implements Adjustable, Accessible

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 specified


value, int extent, int min, int max) 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();
49 | P a g e
}}

Output:

Java JScrollBar Example with AdjustmentListener


import javax.swing.*;
import java.awt.event.*;
class ScrollBarExample
{
ScrollBarExample(){
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());
50 | P a g e
}
});
}
public static void main(String args[])
{
new ScrollBarExample();
}}

Output:

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

51 | P a g e
JMenu class declaration

public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration

public class JMenuItem extends AbstractButton implements Accessible, MenuElem


ent

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);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])

52 | P a g e
{
new MenuExample();
}}

Output:

Example of creating Edit menu for Notepad:


import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);

53 | P a g e
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
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 MenuExample();
}
}

Output:

54 | P a g e
Java JPopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It
inherits the JComponent class.

JPopupMenu class declaration


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

public class JPopupMenu extends JComponent implements Accessible, MenuEleme


nt

Commonly used Constructors:

Constructor Description

JPopupMenu() Constructs a JPopupMenu without an


"invoker".

JPopupMenu(String label) Constructs a JPopupMenu with the specified


title.

55 | P a g e
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:

56 | P a g e
Java JPopupMenu Example with MouseListener and
ActionListener
import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
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(){
57 | P a g e
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);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}
}

Output:

58 | P a g e
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

protecte JCheckBoxMenuItem.AccessibleJCheckBoxMe This class implement


d class nuItem s accessibility
support for the
JcheckBoxMenuItem
class.

Constructor

Constructor Description

JCheckBoxMenuItem() It creates an initially unselected


check box menu item with no set
text or icon.

59 | P a g e
JCheckBoxMenuItem(Action a) It creates a menu item whose
properties are taken from the Action
supplied.

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

AccessibleCont getAccessibleConte It gets the AccessibleContext


ext xt() 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 getUIClassID() It returns the name of the L&F


class that renders this
component.

protected paramString() It returns a string representation


String of this JCheckBoxMenuItem.

void setState(boolean b) It sets the selected-state of the


item.

60 | P a g e
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;
61 | P a g e
Icon newIcon;
if (selected) {
newLabel = "Value-1";
} else {
newLabel = "Value-2";
}
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.

62 | P a g e
JSeparator class declaration
public class JSeparator extends JComponent implements SwingConstants, Accessi
ble

Commonly used Constructors of JSeparator

Constructor Description

JSeparator() Creates a new horizontal separator.

JSeparator(int Creates a new separator with the specified horizontal or


orientation) vertical orientation.

Commonly used Methods of JSeparator

Method Description

void setOrientation(int It is used to set the orientation of the


orientation) separator.

int getOrientation() It is used to return the orientation of the


separator.

Java JSeparator Example 1


import javax.swing.*;
class SeparatorExample
{
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);

63 | P a g e
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 SeparatorExample
{
public static void main(String args[]) {
JFrame f = new JFrame("Separator Example");
f.setLayout(new GridLayout(0, 1));

64 | P a g e
JLabel l1 = new JLabel("Above Separator");
f.add(l1);
JSeparator sep = new JSeparator();
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


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

public class JProgressBar extends JComponent implements SwingConstants, Acces


sible

Commonly used Constructors:

Constructor Description

JProgressBar() It is used to create a horizontal progress bar but no


string text.

65 | P a g e
JProgressBar(int It is used to create a horizontal progress bar with the
min, int max) specified minimum and maximum value.

JProgressBar(int It is used to create a progress bar with the specified


orient) orientation, it can be either Vertical or Horizontal by
using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.

JProgressBar(int It is used to create a progress bar with the specified


orient, int min, int orientation, minimum and maximum value.
max)

Commonly used Methods:

Method Description

void It is used to determine whether string should be


setStringPainted(boolea displayed.
n b)

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 may be either


orientation) 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);
66 | P a g e
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();
}
}

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


67 | P a g e
Let's see the declaration for javax.swing.JTree class.

public class JTree extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

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


value) array as the child of a new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its


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

68 | P a g e
}
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


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

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 It is used to create a color chooser panel with


initialcolor) the specified color initially.

69 | P a g e
Commonly used Methods:

Method Description

void It is used to add a color


addChooserPanel(AbstractColorChooserPanel chooser panel to the
panel) color chooser.

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


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

70 | P a g e
}
}

Output:

Java JColorChooser Example with ActionListener


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample extends JFrame implements ActionListener{
JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);

71 | P a g e
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 ColorChooserExample();
}
}

Output:

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

JTabbedPane class declaration


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

public class JTabbedPane extends JComponent implements Serializable, Accessibl


e, SwingConstants
73 | P a g e
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, Creates an empty TabbedPane with a


int tabLayoutPolicy) 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) {

74 | P a g e
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 creates a slider with the specified orientation set


orientation) by either JSlider.HORIZONTAL or JSlider.VERTICAL
with the range 0 to 100 and initial value 50.

JSlider(int min, int creates a horizontal slider using the given min and
max) max.

JSlider(int min, int creates a horizontal slider using the given min,
max, int value) max and value.

75 | P a g e
JSlider(int creates a slider using the given orientation, min,
orientation, int min, max and value.
int max, int value)

Commonly used Methods of JSlider class

Method Description

public void is used to set the minor tick spacing to


setMinorTickSpacing(int n) the slider.

public void is used to set the major tick spacing to


setMajorTickSpacing(int n) the slider.

public void is used to determine whether tick marks


setPaintTicks(boolean b) are painted.

public void is used to determine whether labels are


setPaintLabels(boolean b) painted.

public void is used to determine whether track is


setPaintTracks(boolean b) painted.

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

76 | P a g e
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);
}
}

Output:

77 | P a g e
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


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

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 It is used to construct a spinner for a given model.


model)

Commonly used Methods:

Method Description

void It is used to add a listener to the list that is


addChangeListener(ChangeListener notified each time a change to the model
listener) 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) {

78 | P a g e
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);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java JSpinner Example with ChangeListener


imp
ort javax.swing.*;
import javax.swing.event.*;
public class SpinnerExample {
public static void main(String[] args) {
JFrame f=new JFrame("Spinner Example");

79 | P a g e
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());
}
});
}
}

Output:

80 | P a g e
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


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

public class JDialog extends Dialog implements WindowConstants, Accessible, Roo


tPaneContainer

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 It is used to create a dialog with the specified title,
title, boolean modal) 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");
81 | P a g e
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


82 | P a g e
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 It is used to create a new JPanel with FlowLayout and


isDoubleBuffered) the specified buffering strategy.

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


layout) layout manager.

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

83 | P a g e
public static void main(String args[])
{
new PanelExample();
}
}

Output:

Java JFileChooser
JFileChooser is a class that is present in the java Swing package. The java Swing
package is essential for JavaTM Foundation Classes(JFC). JFileChooser contains many
elements that assist in building a graphical user Interface in java. Java Swing gives
components like buttons, panels, dialogs, etc. JFileChooser is a simple and successful
method for inciting the client to pick a file or a directory. JFileChooser inherited the
properties of JComponent class and implemented them with an Accessible interface.

Constructors Present in Java JFileChooser Class


JFileChooser():

Constructs a JFileChooser highlighting the client's default directory.

Example program on JFileChooser()

// program to demonstrate the JFileChooser() constructor


84 | P a g e
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser(); // default constructor JFileChooser is called.
jf.showSaveDialog(null);
}
}

Output:

JFileChooser(File currentDirectory):

Constructs a JFileChooser involving the given File as the way.

Example program on JFileChooser(File currentDirectory)

// program to demonstrate the JFileChooser(File currentDirectory) constructor


// importing the required packages
85 | P a g e
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser("c:"); // parameterised constructor JFileChoose
r( File currentDirectory) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

JFileChooser(File currentDirectory, FileSystemViewfsv):

Constructs a JFileChooser utilizing the given current catalog and FileSystemView.

Example program on JFileChooser(File currentDirectory, FileSystemViewfsv)

// program to demonstrate the JFileChooser(File currentDirectory, FileSystemViewfsv)


constructor
86 | P a g e
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser("c:", FileSystemView.getFileSystemView()); //
parameterised constructor JFileChooser(File currentDirectory, FileSystemViewfsv) is c
alled.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

JFileChooser(FileSystemViewfsv):

Constructs a JFileChooser utilizing the given FileSystemView.

Example program on JFileChooser(FileSystemViewfsv)

87 | P a g e
// program to demonstrate the JFileChooser(FileSystemViewfsv) constructor
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser(FileSystemView.getFileSystemView()); // para
meterised constructor JFileChooser(FileSystemViewfsv) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

JFileChooser(String currentDirectoryPath):

Constructs a JFileChooser utilizing the given way.

Example program on JFileChooser(String currentDirectoryPath):

88 | P a g e
// program to demonstrate the JFileChooser(String currentDirectoryPath) constructor
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser("C:\Altaf zameer"); // parameterised construct
or JFileChooser(string current DirectoryPath) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

JFileChooser(String currentDirectoryPath, FileSystemViewfsv):

Constructs a JFileChooser utilizing the given current catalog way and FileSystemView.

Example program on JFileChooser( String currentDirectoryPath, FileSystemViewfsv ):

89 | P a g e
// program to demonstrate the JFileChooser( String currentDirectoryPath, FileSystemVi
ewfsv ) constructor
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser("C:", FileSystemView.getFileSystemView());// param
eterised constructor JFileChooser( String currentDirectoryPath, FileSystemViewfsv ) is
called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

JFileChooser( File ):

Example program on JFileChooser( File ) constructor:


90 | P a g e
// program to demonstrate the JFileChooser( file ) constructor
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooserjf = new JFileChooser(new File(" C:\\Users "));// parameterised const
ructor JFileChooser( file ) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

JFileChooser(File, FileSystemView):

Example on JFileChooser( File, FileSystemView )

// program to demonstrate the JFileChooser( file, FileSystemView ) constructor

91 | P a g e
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
// File class
File f = new File("C:\\Altafzameer\\");
JFileChooserjf = new JFileChooser(f, FileSystemView.getFileSystemView());// para
meterised constructor JFileChooser( file ) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}

Output:

Advantages of JFileChooser()

92 | P a g e
Statement of the JFileChooser() beyond the occasion audience additionally can be
used within the occasion audience.

JFileChooser return esteem, which portrays regardless of whether the record has been
picked.

Boundary given to the accompanying strategy for JFileChooser can confine clients
effectively to choose either record or envelope or both.

The JFileChooser() declaration made external to the event listener can moreover be
utilized inside the event listener.

The JFileChooser return result shows whether the file has been chosen.

The accompanying JFileChooser technique's boundary permits clients to handily be


limited from choosing either a file, a folder, or both.

Methods in JFileChooser Class


The JFileChooser class fundamentally gives three strategies that show the record
chooser discoursed, as in the accompanying:

showOpenDialog(component owner ): This technique opens an exchange box


that contains an endorsement button, as such, "Open", that opens a document from
the discourse.

Syntax:

intshowOpenDialog(component proprietor);

showSaveDialog( component owner ): This strategy is utilized when the client


needs to save the particular document that he/she is utilizing. This exchange box
contains an endorsement button, as such, "Save", to save the document.

Syntax:

intshowSaveDialog(component proprietor);

showDialog(component owner, string): This technique shows an exchange box


with an endorsement button which is client characterized.

Syntax:

intshowDialog(component owner,string);
93 | P a g e
getSelectedFile(): This technique returns the document that is chosen by the client.

Syntax:

filegetSelectedFile();

setCurrentDirectory(File f): This technique sets the ongoing catalog as


determined.

Syntax:

voidsetCurrentDirectory(File f);

getCurrentDirectory(): This technique for JFileChooser returns the ongoing index as


chosen by the client.

Syntax:

filegetCurrentDirectory();

(File f):This strategy returns the name of the document as given by the record
contention.

Syntax:

String getName(File f);

Example
A example program to create a JFrame window:

// java program to create the frame and perform the action in that
// importing the required packages and classes
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld extends JFrame implements ActionListener {

// declaring a Jlable to show the files whichare selected by the user


staticJLabel l;

// a default constructor

94 | P a g e
HelloWorld()
{
}

public static void main(String args[])


{
// // creating an object to the Jframe class and giving the name of the frame
JFrame f = new JFrame(" JavaTpoint");

// fixing the size of the frame


f.setSize(400, 400);

// giving the frame visibility


f.setVisible(true);

// closing the frame


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// creating a JButton to save the dialog


JButton b1 = new JButton("save dialog");

// creating a JButton to open the dialog


JButton b2 = new JButton("open dialog");

// creating an object to the HelloWorld class


HelloWorld f1 = new HelloWorld();

// Using action listener class to capture the response of the user using buttons
b1.addActionListener(f1); // adding b1 button in actionListener
b2.addActionListener(f1); // adding b2 button in actionListener

// Creating a panel to add buttons and labels


JPanel p = new JPanel();

// adding buttons to the frame


p.add(b1);

95 | P a g e
p.add(b2);

// set the label to its initial value


l = new JLabel("no file selected");

// adding the panel to the frame


p.add(l);
f.add(p);

f.show();
}
public void actionPerformed(ActionEvent e)
{
// if the client presses the save button, show the save dialog
String com = e.getActionCommand();

if (com.equals("save")) {
// creating an object to the JFileChooser class
JFileChooserjf = new JFileChooser(FileSystemView.getFileSystemView());

// calling the showsSaveDialog method to display the save dialog on the frame

int r = jf.showSaveDialog(null);

// if the user selects a file


if (r == JFileChooser.APPROVE_OPTION)

{
// setting the label as the path of the selected file
l.setText(jf.getSelectedFile().getAbsolutePath());
}
// if the user canceled the operation
else
l.setText("The user cancelled the operation");
}

96 | P a g e
// if the user presses the open dialog, show the open dialog
else {
// create an object of JFileChooser class
JFileChooserjf = new JFileChooser(FileSystemView.getFileSystemView());

// calling the showOpenDialog method to display the save dialog on the frame
int r = jf.showOpenDialog(null);

// if the user selects a file


if (r == JFileChooser.APPROVE_OPTION)

{
// setting the label as the path of the selected file
l.setText(jf.getSelectedFile().getAbsolutePath());
}
// if the user canceled the operation
else
l.setText("The user cancelled the operation");
}
}
}

Output:

97 | P a g e
98 | P a g e
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.AccessibleJToggleB This class implements


class utton accessibility support for the
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.

99 | P a g e
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 specified


selected) image and selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the


specified text.

JToggleButton(String text, It creates a toggle button with the specified


boolean selected) text and selection state.

JToggleButton(String text, Icon It creates a toggle button that has the specified
icon) text and image, and that is initially unselected.

JToggleButton(String text, Icon It creates a toggle button with the specified


icon, boolean selected) text, image, and selection state.

Methods

Modifier and Method Description


Type

AccessibleConte getAccessibleConte It gets the AccessibleContext


xt xt() 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.

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;

100 | P a g e
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener {


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

Output

101 | P a g e
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 JToolBar.AccessibleJTool This class implements accessibility


class Bar 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 specified name
orientation) and orientation.

102 | P a g e
Useful Methods

Modifier and Type Method Description

JButton add(Action a) It adds a new JButton


which dispatches the
action.

protected void addImpl(Component comp, If a JButton is being


Object constraints, int index) added, it is initially set
to be disabled.

Void addSeparator() It appends a separator


of default size to the
end of the tool bar.

protected createActionChangeListener(JB It returns a properly


PropertyChangeListe utton b) configured
ner PropertyChangeListene
r 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 createActionComponent(Action Factory method which


a) creates the JButton for
Actions added to the
JToolBar.

ToolBarUI getUI() It returns the tool bar's


current UI.

Void setUI(ToolBarUI ui) It sets the L&F object


that renders this
component.

Void setOrientation(int o) It sets the orientation


of the tool bar.

Java JToolBar Example


import java.awt.BorderLayout;
import java.awt.Container;
103 | P a g e
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"));
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:

104 | P a g e
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 JViewport.AccessibleJView This class implements accessibility


class port support for the Jviewport class.

protected JViewport.ViewListener A listener for the view.


class

Fields

Modifier Field Description


and Type

static int BACKINGSTORE_SCROLL_M It draws viewport contents into an


ODE offscreen image.

protected backingStoreImage The view image used for a backing


Image store.

static int BLIT_SCROLL_MODE It uses graphics.copyArea to

105 | P a g e
implement scrolling.

protected isViewSizeSet True when the viewport dimensions


boolean have been determined.

protected lastPaintPosition The last viewPosition that we've


Point painted, so we know how much of
the backing store image is valid.

protected scrollUnderway The scrollUnderway flag is used for


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

Constructor

Constructor Description

JViewport() Creates a JViewport.

Methods

Modifier and Type Method Description

Void addChangeListener(ChangeLis It adds a ChangeListener


tener l) to the list that is notified
each time the view's
size, position, or the
viewport's extent size
has changed.

protected createLayoutManager() Subclassers can override


LayoutManager this to install a different
layout manager (or null)
in the constructor.

protected createViewListener() It creates a listener for


Jviewport.ViewListen the view.
er

Int getScrollMode() It returns the current


scrolling mode.

106 | P a g e
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 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 of the


newExtent) 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 of the


newSize) 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");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Label");


107 | P a g e
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);

JButton jButton1 = new JButton();


jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AL
WAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_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.

Nested Class

108 | P a g e
Modifier and Class Description
Type

protected JFrame.AccessibleJFr This class implements accessibility


class ame support for the JFrame class.

Fields

Modifier and Field Description


Type

protected accessibleContext The accessible context property.


AccessibleContex
t

static int EXIT_ON_CLOSE The exit application default window


close operation.

protected rootPane The JRootPane instance that


JRootPane manages the contentPane and
optional menuBar for this frame, as
well as the glassPane.

protected boolean rootPaneCheckingEna If true then calls to add and


bled setLayout will be forwarded to the
contentPane.

Constructors

Constructor Description

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

JFrame(GraphicsConfiguration It creates a Frame in the specified


gc) GraphicsConfiguration of a screen device and a
blank title.

JFrame(String title) It creates a new, initially invisible Frame with the


specified title.

JFrame(String title, It creates a JFrame with the specified title and


GraphicsConfiguration gc) the specified GraphicsConfiguration of a screen
device.

109 | P a g e
Useful Methods

Modifier and Method Description


Type

protected addImpl(Component comp, Object Adds the specified child


void constraints, int index) Component.

protected createRootPane() Called by the


JRootPane constructor methods 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(bool Provides a hint as to


ean defaultLookAndFeelDecorated) whether or not 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.

TransferHandl getTransferHandler() It gets the


er transferHandler
property.

110 | P a g e
JFrame Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
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 JComponent
111 | P a g e
The JComponent class is the base class of all Swing components except top-level
containers. Swing components whose names begin with "J" are descendants of the
JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame
and JDialog don't inherit JComponent class because they are the child of top-level
containers.

The JComponent class extends the Container class which itself extends Component.
The Container class has support for adding components to the container.

Fields

Modifier and Type Field Description

protected accessibleContext The AccessibleContext


AccessibleContext associated with this
JComponent.

protectedEventList listenerList A list of event listeners for


enerList this component.

static String TOOL_TIP_TEXT_KEY The comment to display


when the cursor is over the
component, also known as a
"value tip", "flyover help",
or "flyover label"

protected ui The look and feel delegate


ComponentUI for this component.

static int UNDEFINED_CONDITION It is a constant used by


some of the APIs to mean
that no condition is defined.

112 | P a g e
static int WHEN_ANCESTOR_OF_FO It is a constant used for
CUSED_COMPONENT registerKeyboardAction that
means that the command
should be invoked when the
receiving component is an
ancestor of the focused
component or is itself the
focused component.

static int WHEN_FOCUSED It is a constant used for


registerKeyboardAction that
means that the command
should be invoked when the
component has the focus.

static int WHEN_IN_FOCUSED_WIND Constant used for


OW registerKeyboardAction that
means that the command
should be invoked when the
receiving component is in
the window that has the
focus or is itself the focused
component.

Constructor

Constructor Description

JComponent() Default JComponent constructor.

Useful Methods

Modifier and Method Description


Type

Void setActionMap(ActionMap It sets the ActionMap to am.


am)

Void setBackground(Color bg) It sets the background color of this

113 | P a g e
component.

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

Void setMaximumSize(Dimensio It sets the maximum size of this


n maximumSize) component to a constant value.

Void setMinimumSize(Dimensio It sets the minimum size of this


n minimumSize) component to a constant value.

protected void setUI(ComponentUI newUI) It sets the look and feel delegate
for this component.

Void setVisible(boolean aFlag) It makes the component visible or


invisible.

Void setForeground(Color fg) It sets the foreground color of this


component.

String getToolTipText(MouseEven It returns the string to be used as


t event) the tooltip for event.

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


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

TransferHandl getTransferHandler() It gets the transferHandler


er property.

Java JComponent Example


import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyJComponent extends JComponent {
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(30, 30, 100, 100);
}
}

114 | P a g e
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the JComponent to main frame
frame.add(com);
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:

115 | P a g e
Constructor Description

JLayeredPane It is used to create a new JLayeredPane

Commonly used Methods:

Method Description

int It is used to return the index of the specified


getIndexOf(Component Component.
c)

int getLayer(Component It is used to return the layer attribute for the specified
c) Component.

int It is used to return the relative position of the


getPosition(Component component within its layer.
c)

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

116 | P a g e
//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:

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 Field Description


and Type

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_MO It indicates that an outline only of the item


DE being dragged should appear inside the

117 | P a g e
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);
setVisible(true);
}
public static void main(String args[])
{
new JDPaneDemo();
}
}
class CustomDesktopPane extends JDesktopPane
{

118 | P a g e
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, tr
ue, 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:

Java JEditorPane
JEditorPane class is used to create a simple text editor window. This class has
setContentType() and setText() methods.

119 | P a g e
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

Modifi Class Description


er and
Type

protect JEditorPane.AccessibleJEditorPane This class implements accessib


ed support for the JEditorPane class
class

protect JEditorPane.AccessibleJEditorPaneHTML This class provides support


ed AccessibleHypertext, and is use
class instances where the Edito
installed in this JEditorPane is
instance of HTMLEditorKit.

protect JEditorPane.JEditorPaneAccessibleHypert What's returned


ed extSupport AccessibleJEditorPaneHTML.getA
class ssibleText

Fields

Modifier Field Description


and Type

static HONOR_DISPLAY_PROPER Key for a client property used to


String TIES 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 W3C_LENGTH_UNITS Key for a client property used to


String indicate whether w3c compliant length
units are used for html rendering.

Constructors

Constructor Description

120 | P a g e
JEditorPane() It creates a new JEditorPane.

JEditorPane(String url) It creates a JEditorPane based on a string containing


a URL specification.

JEditorPane(String type, It creates a JEditorPane that has been initialized to


String text) 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(HyperlinkList Adds a hyperlink listener for


ener 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 type) It sets the type of content that


this editor handles.

Void setPage(URL page) It sets the current URL being


displayed.

Void read(InputStream in, Object desc) This method initializes from a


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

121 | P a g e
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.

String getText() It returns the text contained in


this TextComponent in terms
of the content type of this
editor.

Void read(InputStream in, Object desc) This method initializes from a


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 stud
ies."
+ " Doctors advise that the sleeping at improper timings may lead for obesi
ty during the students days.");
myFrame.setContentPane(myPane);
122 | P a g e
myFrame.setVisible(true);
}
}

Output:

JEditorPane Example: using HTML


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/html");

123 | P a g e
myPane.setText("<h1>Sleeping</h1><p>Sleeping is necessary for a healthy bo
dy."
+ " But sleeping in unnecessary times may spoil our health, wealth and stud
ies."
+ " Doctors advise that the sleeping at improper timings may lead for obesi
ty 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.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when


present, sets the scroll pane's client. The two int
JScrollPane(Component

124 | P a g e
)

JScrollPane(int, int)
parameters, when present, set the vertical and horizontal
JScrollPane(Component
scroll bar policies (respectively).
, int, int)

Useful Methods

Modifier Method Description

Void setColumnHeaderView(Compo It sets the column header for the


nent) scroll pane.

Void setRowHeaderView(Componen It sets the row header for the scroll


t) pane.

Void setCorner(String, Component) It sets or gets the specified corner.


The int parameter specifies which
Compone getCorner(String) corner and must be one of the
nt following constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

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

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

public class JScrollPaneExample {


private static final long serialVersionUID = 1L;

125 | P a g e
private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scroll Pane Example");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// set flow layout for the frame


frame.getContentPane().setLayout(new FlowLayout());

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollableTextArea = new JScrollPane(textArea);

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLL
BAR_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:
126 | P a g e
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.

Nested Class

Modifier and Class Description


Type

protected JSplitPane.AccessibleJSplitP This class implements accessibility


class ane support for the JsplitPane class.

Useful Fields

Modifier and Field Description


Type

static String BOTTOM It use to add a Component


below the other Component.

127 | P a g e
static String CONTINUOUS_LAYOUT_PROPE Bound property name for
RTY continuousLayout.

static String DIVIDER It uses to add a Component that


will represent the divider.

static int HORIZONTAL_SPLIT Horizontal split indicates the


Components are split along the
x axis.

protected int lastDividerLocation Previous location of the split


pane.

protected leftComponent The left or top component.


Component

static int VERTICAL_SPLIT Vertical split indicates the


Components are split along the
y axis.

protected rightComponent The right or bottom component.


Component

protected int orientation How the views are split.

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, boolean It creates a new JsplitPane with the


newContinuousLayout) specified orientation and redrawing
style.

JSplitPane(int newOrientation, boolean It creates a new JsplitPane with the


newContinuousLayout, Component specified orientation and redrawing
newLeftComponent, Component style, and with the specified
newRightComponent) components.

JSplitPane(int newOrientation, Component It creates a new JsplitPane with the


newLeftComponent, Component specified orientation and the specified

128 | P a g e
newRightComponent) components.

Useful Methods

Modifier and Method Description


Type

protected void addImpl(Component comp, It cdds the specified


Object constraints, int index) component to this split pane.

AccessibleConte getAccessibleContext() It gets the AccessibleContext


xt associated with this
JSplitPane.

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, or how


orientation) the splitter is divided.

JSplitPane Example
import java.awt.FlowLayout;
129 | P a g e
import java.awt.Panel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
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" };
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, pa
nel2);
// 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();
}
});

130 | P a g e
}
}

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.

Constructors

Constructor Description

JTextPane() It creates a new JTextPane.

JtextPane(StyledDocument It creates a new JTextPane, with a specified


doc) document model.

Useful Methods

Modifier and Method Description


Type

131 | P a g e
Style addStyle(String nm, Style parent) It adds a new style into
the logical style
hierarchy.

AttributeSet getCharacterAttributes() It fetches the character


attributes in effect at the
current location of the
caret, or null.

StyledDocume getStyledDocument() It fetches the model


nt associated with the
editor.

Void setDocument(Document doc) It associates the editor


with a text document.

Void setCharacterAttributes(AttributeSet It applies the given


attr, boolean replace) attributes to character
content.

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 setStyledDocument(StyledDocumen It associates the editor


t doc) with a text document.

JTextPane Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

132 | P a g e
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);

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

133 | P a g e
Java JRootPane
JRootPane is a lightweight container used behind the scenes by JFrame, JDialog,
JWindow, JApplet, and JInternalFrame.

Nested Classes

Modifier Class Description


and Type

protected JRootPane.AccessibleJRootP This class implements accessibility


class ane support for the JRootPane class.

protected JRootPane.RootLayout A custom layout manager that is


class responsible for the layout of
layeredPane, glassPane, and
menuBar.

Fields

Modifier Field Description


and Type

static int COLOR_CHOOSER_DIAL Constant used for the


OG windowDecorationStyle property.

134 | P a g e
protected contentPane The content pane.
JButton

protected defaultButton The button that gets activated when the


Container pane has the focus and a UI-specific
action like pressing the Enter key
occurs.

protected menuBar The menu bar.


JMenuBar

protected glassPane The glass pane that overlays the menu


Component bar and content pane, so it can
intercept mouse movements and such.

static int ERROR_DIALOG Constant used for the


windowDecorationStyle property.

Constructor

Constructor Description

JRootPane() Creates a JRootPane, setting up its glassPane, layeredPane, and


contentPane.

Useful Methods

Modifier and Method Description


Type

protected void addImpl(Component comp, Overridden to enforce the


Object constraints, int index) position of the glass
component as the zero child.

Void addNotify() Notifies this component that it


now has a parent component.

protected createContentPane() It is called by the constructor


Container methods to create the default
contentPane.

protected createGlassPane() It called by the constructor


Component methods to create the default
glassPane.

135 | P a g e
AccessibleConte getAccessibleContext() It gets the AccessibleContext
xt 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


defaultButton) property, which determines
the current default button for
this JRootPane.

Void setJMenuBar(JMenuBar It adds or changes the menu


menu) bar used in the layered pane.

JRootPane Example
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JRootPane;

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

136 | P a g e
// Add a button to the content pane
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

137 | P a g e
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 {

138 | P a g e
IconExample(){
Frame f=new Frame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[]){
new IconExample();
}
}

Output:

Example to change TitleBar icon in Java Swing


import javax.swing.*;
import java.awt.*;
class IconExample {
IconExample(){
JFrame f=new JFrame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(200,200);
f.setVisible(true);

139 | P a g e
}
public static void main(String args[]){
new ToolkitExample();
}
}

Output:

How to make an executable jar file in Java


The jar (Java Archive) tool of JDK provides the facility to create the executable jar
file. An executable jar file calls the main method of the class if you double click it.

To create the executable jar file, you need to create .mf file, also known as manifest
file.

Creating manifest file


To create manifest file, you need to write Main-Class, then colon, then space, then
classname then enter. For example:

myfile.mf

Main-Class: First

As you can see, the mf file starts with Main-Class colon space class name. Here, class
name is First.

In mf file, new line is must after the class name.

Creating executable jar file using jar tool


The jar tool provides many switches, some of them are as follows:
140 | P a g e
-c creates new archive file

-v generates verbose output. It displays the included or extracted resource on the


standard output.

-m includes manifest information from the given mf file.

-f specifies the archive file name

-x extracts files from the archive file

Now, let's write the code to generated the executable jar using mf file.

You need to write jar then swiches then mf_file then jar_file then .classfile as
given below:

jar -cvmf myfile.mf myjar.jar First.class

It is shown in the image given below:

Now it will create the executable jar file. If you double click on it, it will call the main
method of the First class.

We are assuming that you have created any window based application using AWT or
SWING. If you don't, you can use the code given below:

First.java

import javax.swing.*;
public class First{

141 | P a g e
First(){
JFrame f=new JFrame();

JButton b=new JButton("click");


b.setBounds(130,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 First();
}
}
Download this example

Let's see how executable jar file looks by the image given below:

142 | P a g e
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();

t = new Thread(this);
t.start();

143 | P a g e
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) { }
}

public void printTime(){


b.setText(timeString);
}

public static void main(String[] args) {

144 | P a g e
new DigitalWatch();

}
}

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

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

145 | P a g e
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);

146 | P a g e
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);

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

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:

147 | P a g e
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("p3.gif");
g.drawImage(i, 120,100,this);

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

Example of creating Edit menu for Notepad:


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

public class Notepad implements ActionListener{


JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;

Notepad(){
f=new JFrame();
148 | P a g e
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();
mb.setBounds(5,5,400,40);

file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");

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,30,460,460);

f.add(mb);f.add(ta);

f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if(e.getSource()==cut)
ta.cut();

149 | P a g e
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 Notepad();
}
}

Example of open dialog box:


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

public class OpenMenu extends JFrame implements ActionListener{


JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
OpenMenu(){
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);
150 | P a g e
add(mb);
add(ta);

}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
openFile();
}
}

void openFile(){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);

if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();

displayContent(filepath);

void displayContent(String fpath){


try{
BufferedReader br=new BufferedReader(new FileReader(fpath));
String s1="",s2="";

while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception e) {e.printStackTrace(); }

151 | P a g e
}

public static void main(String[] args) {


OpenMenu om=new OpenMenu();
om.setSize(800,800);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Notepad in Java with source code


Notepad in Java with source code: We can develop Notepad in java with the help
of AWT/Swing with event handling. Let's see the code of creating Notepad in java.

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

/************************************/
class FileOperation
{
Notepad npd;

boolean saved;
boolean newFileFlag;
String fileName;
String applicationTitle="Notepad - JavaTpoint";

File fileRef;
JFileChooser chooser;
/////////////////////////////
152 | P a g e
boolean isSave(){return saved;}
void setSave(boolean saved){this.saved=saved;}
String getFileName(){return new String(fileName);}
void setFileName(String fileName){this.fileName=new String(fileName);}
/////////////////////////
FileOperation(Notepad npd)
{
this.npd=npd;

saved=true;
newFileFlag=true;
fileName=new String("Untitled");
fileRef=new File(fileName);
this.npd.f.setTitle(fileName+" - "+applicationTitle);

chooser=new JFileChooser();
chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java)"));
chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
chooser.setCurrentDirectory(new File("."));

}
//////////////////////////////////////

boolean saveFile(File temp)


{
FileWriter fout=null;
try
{
fout=new FileWriter(temp);
fout.write(npd.ta.getText());
}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{fout.close();}catch(IOException excp){}}
updateStatus(temp,true);
return true;

153 | P a g e
}
////////////////////////
boolean saveThisFile()
{

if(!newFileFlag)
{return saveFile(fileRef);}

return saveAsFile();
}
////////////////////////////////////
boolean saveAsFile()
{
File temp=null;
chooser.setDialogTitle("Save As...");
chooser.setApproveButtonText("Save Now");
chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
chooser.setApproveButtonToolTipText("Click me to save!");

do
{
if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return false;
temp=chooser.getSelectedFile();
if(!temp.exists()) break;
if( JOptionPane.showConfirmDialog(
this.npd.f,"<html>"+temp.getPath()+" already exists.<br>Do you want to replace
it?<html>",
"Save As",JOptionPane.YES_NO_OPTION
)==JOptionPane.YES_OPTION)
break;
}while(true);

return saveFile(temp);
}

154 | P a g e
////////////////////////
boolean openFile(File temp)
{
FileInputStream fin=null;
BufferedReader din=null;

try
{
fin=new FileInputStream(temp);
din=new BufferedReader(new InputStreamReader(fin));
String str=" ";
while(str!=null)
{
str=din.readLine();
if(str==null)
break;
this.npd.ta.append(str+"\n");
}

}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{din.close();fin.close();}catch(IOException excp){}}
updateStatus(temp,true);
this.npd.ta.setCaretPosition(0);
return true;
}
///////////////////////
void openFile()
{
if(!confirmSave()) return;
chooser.setDialogTitle("Open File...");
chooser.setApproveButtonText("Open this");
chooser.setApproveButtonMnemonic(KeyEvent.VK_O);
chooser.setApproveButtonToolTipText("Click me to open the selected file.!");

155 | P a g e
File temp=null;
do
{
if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return;
temp=chooser.getSelectedFile();

if(temp.exists()) break;

JOptionPane.showMessageDialog(this.npd.f,
"<html>"+temp.getName()+"<br>file not found.<br>"+
"Please verify the correct file name was given.<html>",
"Open", JOptionPane.INFORMATION_MESSAGE);

} while(true);

this.npd.ta.setText("");

if(!openFile(temp))
{
fileName="Untitled"; saved=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
if(!temp.canWrite())
newFileFlag=true;

}
////////////////////////
void updateStatus(File temp,boolean saved)
{
if(saved)
{
this.saved=true;
fileName=new String(temp.getName());
if(!temp.canWrite())

156 | P a g e
{fileName+="(Read only)"; newFileFlag=true;}
fileRef=temp;
npd.f.setTitle(fileName + " - "+applicationTitle);
npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
newFileFlag=false;
}
else
{
npd.statusBar.setText("Failed to save/open : "+temp.getPath());
}
}
///////////////////////
boolean confirmSave()
{
String strMsg="<html>The text in the "+fileName+" file has been changed.<br>"+
"Do you want to save the changes?<html>";
if(!saved)
{
int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,
JOptionPane.YES_NO_CANCEL_OPTION);

if(x==JOptionPane.CANCEL_OPTION) return false;


if(x==JOptionPane.YES_OPTION && !saveAsFile()) return false;
}
return true;
}
///////////////////////////////////////
void newFile()
{
if(!confirmSave()) return;

this.npd.ta.setText("");
fileName=new String("Untitled");
fileRef=new File(fileName);
saved=true;
newFileFlag=true;

157 | P a g e
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
//////////////////////////////////////
}// end defination of class FileOperation
/************************************/
public class Notepad implements ActionListener, MenuConstants
{

JFrame f;
JTextArea ta;
JLabel statusBar;

private String fileName="Untitled";


private boolean saved=true;
String applicationName="Javapad";

String searchString, replaceString;


int lastSearchIndex;

FileOperation fileHandler;
FontChooser fontDialog=null;
FindDialog findReplaceDialog=null;
JColorChooser bcolorChooser=null;
JColorChooser fcolorChooser=null;
JDialog backgroundDialog=null;
JDialog foregroundDialog=null;
JMenuItem cutItem,copyItem, deleteItem, findItem, findNextItem,
replaceItem, gotoItem, selectAllItem;
/****************************/
Notepad()
{
f=new JFrame(fileName+" - "+applicationName);
ta=new JTextArea(30,60);
statusBar=new JLabel("|| Ln 1, Col 1 ",JLabel.RIGHT);
f.add(new JScrollPane(ta),BorderLayout.CENTER);
f.add(statusBar,BorderLayout.SOUTH);

158 | P a g e
f.add(new JLabel(" "),BorderLayout.EAST);
f.add(new JLabel(" "),BorderLayout.WEST);
createMenuBar(f);
//f.setSize(350,350);
f.pack();
f.setLocation(100,50);
f.setVisible(true);
f.setLocation(150,50);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

fileHandler=new FileOperation(this);

/////////////////////

ta.addCaretListener(
new CaretListener()
{
public void caretUpdate(CaretEvent e)
{
int lineNumber=0, column=0, pos=0;

try
{
pos=ta.getCaretPosition();
lineNumber=ta.getLineOfOffset(pos);
column=pos-ta.getLineStartOffset(lineNumber);
}catch(Exception excp){}
if(ta.getText().length()==0){lineNumber=0; column=0;}
statusBar.setText("|| Ln "+(lineNumber+1)+", Col "+(column+1));
}
});
//////////////////
DocumentListener myListener = new DocumentListener()
{
public void changedUpdate(DocumentEvent e){fileHandler.saved=false;}
public void removeUpdate(DocumentEvent e){fileHandler.saved=false;}

159 | P a g e
public void insertUpdate(DocumentEvent e){fileHandler.saved=false;}
};
ta.getDocument().addDocumentListener(myListener);
/////////
WindowListener frameClose=new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
if(fileHandler.confirmSave())System.exit(0);
}
};
f.addWindowListener(frameClose);
//////////////////
/*
ta.append("Hello dear hello hi");
ta.append("\nwho are u dear mister hello");
ta.append("\nhello bye hel");
ta.append("\nHello");
ta.append("\nMiss u mister hello hell");
fileHandler.saved=true;
*/
}
////////////////////////////////////
void goTo()
{
int lineNumber=0;
try
{
lineNumber=ta.getLineOfOffset(ta.getCaretPosition())+1;
String tempStr=JOptionPane.showInputDialog(f,"Enter Line Number:",""+lineNumber);

if(tempStr==null)
{return;}
lineNumber=Integer.parseInt(tempStr);
ta.setCaretPosition(ta.getLineStartOffset(lineNumber-1));
}catch(Exception e){}

160 | P a g e
}
///////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String cmdText=ev.getActionCommand();
////////////////////////////////////
if(cmdText.equals(fileNew))
fileHandler.newFile();
else if(cmdText.equals(fileOpen))
fileHandler.openFile();
////////////////////////////////////
else if(cmdText.equals(fileSave))
fileHandler.saveThisFile();
////////////////////////////////////
else if(cmdText.equals(fileSaveAs))
fileHandler.saveAsFile();
////////////////////////////////////
else if(cmdText.equals(fileExit))
{if(fileHandler.confirmSave())System.exit(0);}
////////////////////////////////////
else if(cmdText.equals(filePrint))
JOptionPane.showMessageDialog(
Notepad.this.f,
"Get ur printer repaired first! It seems u dont have one!",
"Bad Printer",
JOptionPane.INFORMATION_MESSAGE
);
////////////////////////////////////
else if(cmdText.equals(editCut))
ta.cut();
////////////////////////////////////
else if(cmdText.equals(editCopy))
ta.copy();
////////////////////////////////////
else if(cmdText.equals(editPaste))
ta.paste();

161 | P a g e
////////////////////////////////////
else if(cmdText.equals(editDelete))
ta.replaceSelection("");
////////////////////////////////////
else if(cmdText.equals(editFind))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,true);//find
}
////////////////////////////////////
else if(cmdText.equals(editFindNext))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text

if(findReplaceDialog==null)
statusBar.setText("Use Find option of Edit Menu first !!!!");
else
findReplaceDialog.findNextWithSelection();
}
////////////////////////////////////
else if(cmdText.equals(editReplace))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text

if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,false);//replace
}
////////////////////////////////////
else if(cmdText.equals(editGoTo))
{

162 | P a g e
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
goTo();
}
////////////////////////////////////
else if(cmdText.equals(editSelectAll))
ta.selectAll();
////////////////////////////////////
else if(cmdText.equals(editTimeDate))
ta.insert(new Date().toString(),ta.getSelectionStart());
////////////////////////////////////
else if(cmdText.equals(formatWordWrap))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
ta.setLineWrap(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(formatFont))
{
if(fontDialog==null)
fontDialog=new FontChooser(ta.getFont());

if(fontDialog.showDialog(Notepad.this.f,"Choose a font"))
Notepad.this.ta.setFont(fontDialog.createFont());
}
////////////////////////////////////
else if(cmdText.equals(formatForeground))
showForegroundColorDialog();
////////////////////////////////////
else if(cmdText.equals(formatBackground))
showBackgroundColorDialog();
////////////////////////////////////

else if(cmdText.equals(viewStatusBar))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();

163 | P a g e
statusBar.setVisible(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(helpAboutNotepad))
{
JOptionPane.showMessageDialog(Notepad.this.f,aboutText,"Dedicated 2 u!",
JOptionPane.INFORMATION_MESSAGE);
}
else
statusBar.setText("This "+cmdText+" command is yet to be implemented");
}//action Performed
////////////////////////////////////
void showBackgroundColorDialog()
{
if(bcolorChooser==null)
bcolorChooser=new JColorChooser();
if(backgroundDialog==null)
backgroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatBackground,
false,
bcolorChooser,
new ActionListener()
{public void actionPerformed(ActionEvent evvv){
Notepad.this.ta.setBackground(bcolorChooser.getColor());}},
null);

backgroundDialog.setVisible(true);
}
////////////////////////////////////
void showForegroundColorDialog()
{
if(fcolorChooser==null)
fcolorChooser=new JColorChooser();
if(foregroundDialog==null)
foregroundDialog=JColorChooser.createDialog

164 | P a g e
(Notepad.this.f,
formatForeground,
false,
fcolorChooser,
new ActionListener()
{public void actionPerformed(ActionEvent evvv){
Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
null);

foregroundDialog.setVisible(true);
}

///////////////////////////////////
JMenuItem createMenuItem(String s, int key,JMenu toMenu,ActionListener al)
{
JMenuItem temp=new JMenuItem(s,key);
temp.addActionListener(al);
toMenu.add(temp);

return temp;
}
////////////////////////////////////
JMenuItem createMenuItem(String s, int key,JMenu toMenu,int aclKey,ActionListener
al)
{
JMenuItem temp=new JMenuItem(s,key);
temp.addActionListener(al);
temp.setAccelerator(KeyStroke.getKeyStroke(aclKey,ActionEvent.CTRL_MASK));
toMenu.add(temp);

return temp;
}
////////////////////////////////////
JCheckBoxMenuItem createCheckBoxMenuItem(String s,
int key,JMenu toMenu,ActionListener al)
{

165 | P a g e
JCheckBoxMenuItem temp=new JCheckBoxMenuItem(s);
temp.setMnemonic(key);
temp.addActionListener(al);
temp.setSelected(false);
toMenu.add(temp);

return temp;
}
////////////////////////////////////
JMenu createMenu(String s,int key,JMenuBar toMenuBar)
{
JMenu temp=new JMenu(s);
temp.setMnemonic(key);
toMenuBar.add(temp);
return temp;
}
/*********************************/
void createMenuBar(JFrame f)
{
JMenuBar mb=new JMenuBar();
JMenuItem temp;

JMenu fileMenu=createMenu(fileText,KeyEvent.VK_F,mb);
JMenu editMenu=createMenu(editText,KeyEvent.VK_E,mb);
JMenu formatMenu=createMenu(formatText,KeyEvent.VK_O,mb);
JMenu viewMenu=createMenu(viewText,KeyEvent.VK_V,mb);
JMenu helpMenu=createMenu(helpText,KeyEvent.VK_H,mb);

createMenuItem(fileNew,KeyEvent.VK_N,fileMenu,KeyEvent.VK_N,this);
createMenuItem(fileOpen,KeyEvent.VK_O,fileMenu,KeyEvent.VK_O,this);
createMenuItem(fileSave,KeyEvent.VK_S,fileMenu,KeyEvent.VK_S,this);
createMenuItem(fileSaveAs,KeyEvent.VK_A,fileMenu,this);
fileMenu.addSeparator();
temp=createMenuItem(filePageSetup,KeyEvent.VK_U,fileMenu,this);
temp.setEnabled(false);
createMenuItem(filePrint,KeyEvent.VK_P,fileMenu,KeyEvent.VK_P,this);

166 | P a g e
fileMenu.addSeparator();
createMenuItem(fileExit,KeyEvent.VK_X,fileMenu,this);

temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,this);
temp.setEnabled(false);
editMenu.addSeparator();
cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this);
copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_C,this);
createMenuItem(editPaste,KeyEvent.VK_P,editMenu,KeyEvent.VK_V,this);
deleteItem=createMenuItem(editDelete,KeyEvent.VK_L,editMenu,this);
deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
editMenu.addSeparator();
findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,this);
findNextItem=createMenuItem(editFindNext,KeyEvent.VK_N,editMenu,this);
findNextItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
replaceItem=createMenuItem(editReplace,KeyEvent.VK_R,editMenu,KeyEvent.VK_H,t
his);
gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_G,this);
editMenu.addSeparator();
selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEvent.VK_A,
this);
createMenuItem(editTimeDate,KeyEvent.VK_D,editMenu,this)
.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));

createCheckBoxMenuItem(formatWordWrap,KeyEvent.VK_W,formatMenu,this);

createMenuItem(formatFont,KeyEvent.VK_F,formatMenu,this);
formatMenu.addSeparator();
createMenuItem(formatForeground,KeyEvent.VK_T,formatMenu,this);
createMenuItem(formatBackground,KeyEvent.VK_P,formatMenu,this);

createCheckBoxMenuItem(viewStatusBar,KeyEvent.VK_S,viewMenu,this).setSelected(
true);
/************For Look and Feel***/
LookAndFeelMenu.createLookAndFeelMenuItem(viewMenu,this.f);

167 | P a g e
temp=createMenuItem(helpHelpTopic,KeyEvent.VK_H,helpMenu,this);
temp.setEnabled(false);
helpMenu.addSeparator();
createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);

MenuListener editMenuListener=new MenuListener()


{
public void menuSelected(MenuEvent evvvv)
{
if(Notepad.this.ta.getText().length()==0)
{
findItem.setEnabled(false);
findNextItem.setEnabled(false);
replaceItem.setEnabled(false);
selectAllItem.setEnabled(false);
gotoItem.setEnabled(false);
}
else
{
findItem.setEnabled(true);
findNextItem.setEnabled(true);
replaceItem.setEnabled(true);
selectAllItem.setEnabled(true);
gotoItem.setEnabled(true);
}
if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
{
cutItem.setEnabled(false);
copyItem.setEnabled(false);
deleteItem.setEnabled(false);
}
else
{
cutItem.setEnabled(true);
copyItem.setEnabled(true);

168 | P a g e
deleteItem.setEnabled(true);
}
}
public void menuDeselected(MenuEvent evvvv){}
public void menuCanceled(MenuEvent evvvv){}
};
editMenu.addMenuListener(editMenuListener);
f.setJMenuBar(mb);
}
/*************Constructor**************/
////////////////////////////////////
public static void main(String[] s)
{
new Notepad();
}
}
/**************************************/
//public
interface MenuConstants
{
final String fileText="File";
final String editText="Edit";
final String formatText="Format";
final String viewText="View";
final String helpText="Help";

final String fileNew="New";


final String fileOpen="Open...";
final String fileSave="Save";
final String fileSaveAs="Save As...";
final String filePageSetup="Page Setup...";
final String filePrint="Print";
final String fileExit="Exit";

final String editUndo="Undo";


final String editCut="Cut";

169 | P a g e
final String editCopy="Copy";
final String editPaste="Paste";
final String editDelete="Delete";
final String editFind="Find...";
final String editFindNext="Find Next";
final String editReplace="Replace";
final String editGoTo="Go To...";
final String editSelectAll="Select All";
final String editTimeDate="Time/Date";

final String formatWordWrap="Word Wrap";


final String formatFont="Font...";
final String formatForeground="Set Text color...";
final String formatBackground="Set Pad color...";

final String viewStatusBar="Status Bar";

final String helpHelpTopic="Help Topic";


final String helpAboutNotepad="About Javapad";

final String aboutText="Your Javapad";


}

170 | P a g e
171 | P a g e

You might also like