Java Swing
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.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
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?
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
We can write the code of swing inside the main(), constructor or any other 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
}
}
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
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example
that sets the position of the button.
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);
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
OpenDialog Box
Notepad
Puzzle 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.
Constructor Description
Methods Description
7 | Page
on the button.
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.
Constructor Description
Methods Description
11 | P a g e
void setHorizontalAlignment(int It sets the alignment of the label's
alignment) contents along the X axis.
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.
Constructor Description
14 | P a g e
specified text.
Methods Description
15 | P a g e
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
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
Constructor Description
JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.
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.
Constructor Description
22 | P a g e
Output:
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.
Constructor Description
Methods Description
25 | P a g e
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
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.
Constructor Description
30 | P a g e
JRadioButton(String s, boolean Creates a radio button with the specified
selected) text and selected status.
Methods Description
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:
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.
Constructor Description
Methods Description
34 | P a g e
addActionListener(ActionListener
a)
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.
Constructor Description
37 | P a g e
JTable() Creates a table with empty
cells.
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:
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.
40 | P a g e
Commonly used Constructors:
Constructor Description
Methods Description
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:
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.
Methods Description
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:
Output:
Output:
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.
Constructor Description
Output:
Output:
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.
51 | P a g e
JMenu class declaration
52 | P a g e
{
new MenuExample();
}}
Output:
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.
Constructor Description
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
Constructor
Constructor Description
59 | P a g e
JCheckBoxMenuItem(Action a) It creates a menu item whose
properties are taken from the Action
supplied.
Methods
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;
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
Constructor Description
Method Description
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:
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.
Constructor Description
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.
Method Description
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.
Constructor Description
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.
Constructor Description
69 | P a g e
Commonly used Methods:
Method Description
70 | P a g e
}
}
Output:
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.
Constructor Description
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.
Constructor Description
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)
Method Description
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);
}
76 | P a g e
Output:
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);
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.
Constructor Description
Method Description
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:
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.
Constructor Description
JDialog(Frame owner, String It is used to create a dialog with the specified title,
title, boolean modal) owner Frame and modality.
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.
Constructor Description
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.
Output:
JFileChooser(File currentDirectory):
Output:
Output:
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):
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:
Constructs a JFileChooser utilizing the given current catalog way and FileSystemView.
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 ):
Output:
JFileChooser(File, FileSystemView):
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.
Syntax:
intshowOpenDialog(component proprietor);
Syntax:
intshowSaveDialog(component proprietor);
Syntax:
intshowDialog(component owner,string);
93 | P a g e
getSelectedFile(): This technique returns the document that is chosen by the client.
Syntax:
filegetSelectedFile();
Syntax:
voidsetCurrentDirectory(File f);
Syntax:
filegetCurrentDirectory();
(File f):This strategy returns the name of the document as given by the record
contention.
Syntax:
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 {
// a default constructor
94 | P a g e
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
95 | P a g e
p.add(b2);
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);
{
// 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);
{
// 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
Constructors
Constructor Description
99 | P a g e
JToggleButton(Action a) It creates a toggle button where properties are
taken from the Action supplied.
JToggleButton(String text, Icon It creates a toggle button that has the specified
icon) text and image, and that is initially unselected.
Methods
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;
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
Constructors
Constructor Description
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
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
Fields
105 | P a g e
implement scrolling.
Constructor
Constructor Description
Methods
106 | P a g e
Component getView() It returns the JViewport's
one child or null.
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);
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
Fields
Constructors
Constructor Description
109 | P a g e
Useful Methods
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
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.
Constructor
Constructor Description
Useful Methods
113 | P a g e
component.
protected void setUI(ComponentUI newUI) It sets the look and feel delegate
for this component.
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.
115 | P a g e
Constructor Description
Method Description
int getLayer(Component It is used to return the layer attribute for the specified
c) Component.
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
117 | P a g e
desktop pane.
Constructor
Constructor Description
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);
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.
Nested Classes
Fields
Constructors
Constructor Description
120 | P a g e
JEditorPane() It creates a new JEditorPane.
Useful Methods
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.
JEditorPane Example
import javax.swing.JEditorPane;
import javax.swing.JFrame;
Output:
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
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
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
125 | P a g e
private static void createAndShowGUI() {
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() {
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
Useful Fields
127 | P a g e
static String CONTINUOUS_LAYOUT_PROPE Bound property name for
RTY continuousLayout.
Constructors
Constructor Description
128 | P a g e
newRightComponent) components.
Useful Methods
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
Useful Methods
131 | P a g e
Style addStyle(String nm, Style parent) It adds a new style into
the logical style
hierarchy.
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);
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
Fields
134 | P a g e
protected contentPane The content pane.
JButton
Constructor
Constructor Description
Useful Methods
135 | P a g e
AccessibleConte getAccessibleContext() It gets the AccessibleContext
xt associated with this JRootPane.
JRootPane Example
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JRootPane;
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
For example, to add tool tip to PasswordField, you need to add only one line of code:
137 | P a g e
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
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.
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:
139 | P a g e
}
public static void main(String args[]){
new ToolkitExample();
}
}
Output:
To create the executable jar file, you need to create .mf file, also known as manifest
file.
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.
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:
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();
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);
}
printTime();
144 | P a g e
new DigitalWatch();
}
}
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 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.
import java.awt.*;
import javax.swing.JFrame;
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);
}
147 | P a g e
import java.awt.*;
import javax.swing.JFrame;
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);
}
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);
}
149 | P a g e
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
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);
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception e) {e.printStackTrace(); }
151 | P a g e
}
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("."));
}
//////////////////////////////////////
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);
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;
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);
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";
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";
170 | P a g e
171 | P a g e