Swing
Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
AWT Swing
AWT components are platform- Java swing components are platform-
dependent. independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look Swing supports pluggable look and
and feel. feel.
AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
MADHAVI 1
Java Swing
MADHAVI 2
Java Swing
Output:
MADHAVI 4
Java Swing
Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed. It inherits AbstractButton class.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and
icon.
JButton(String s) It creates a button with the
specified text.
JButton(Icon i) It creates a button with the
specified icon object.
Commonly used Methods of AbstractButton class:
Methods Description
void setText(String s) It is used to set specified text on
button
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable
the button.
void setIcon(Icon b) It is used to set the specified
Icon on the button.
Icon getIcon() It is used to get the Icon of the
button.
void setMnemonic(int a) It is used to set the mnemonic
on the button.
void It is used to add the action
addActionListener(ActionListener a) listener to this object.
Java JButton Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
MADHAVI 5
Java Swing
}
}
Output:
MADHAVI 6
Java Swing
Java JLabel
The object of JLabel class is a component for placing text in a container.
It is used to display a single line of read only text. The text can be
changed by an application but a user cannot edit it directly. It inherits
JComponent class.
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants,
Accessible
MADHAVI 7
Java Swing
Output:
MADHAVI 9
Java Swing
Output:
Java JTextField
The object of a JTextField class is a text component that allows the
editing of a single line text. It inherits JTextComponent class.
JTextField class declaration
public class JTextField extends JTextComponent implements
SwingConstants
Commonly used Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized
with the specified text.
JTextField(String text, int Creates a new TextField initialized
columns) with the specified text and
columns.
JTextField(int columns) Creates a new empty TextField
with the specified number of
columns.
Commonly used Methods:
Methods Description
void It is used to add the specified
addActionListener(ActionListener l) action listener to receive action
events from this textfield.
Action getAction() It returns the currently set
Action for this ActionEvent
source, or null if no Action is
set.
void setFont(Font f) It is used to set the current font.
void It is used to remove the
removeActionListener(ActionListener specified action listener so that
l)
1
MADHAVI
0
Java Swing
TextFieldExample1(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample1();
}}
1
MADHAVI
2
Java Swing
Output:
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It
allows the editing of multiple line text. It inherits JTextComponent class
JTextArea class declaration
public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no
text initially.
JTextArea(String s) Creates a text area that displays
specified text initially.
JTextArea(int row, int column) Creates a text area with the
specified number of rows and
columns that displays no text
initially.
JTextArea(String s, int row, int Creates a text area with the
column) specified number of rows and
columns that displays specified
text.
Commonly used Methods:
Methods Description
void setRows(int rows) It is used to set specified number
of rows.
void setColumns(int cols) It is used to set specified number
of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified
text on the specified position.
void append(String s) It is used to append the given text
to the end of the document.
1
MADHAVI
3
Java Swing
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample1();
}
}
Output:
1
MADHAVI
5
Java Swing
Java JPasswordField
The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text. It inherits
JTextField class.
JPasswordField class declaration
public class JPasswordField extends JTextField
Commonly used Constructors:
Constructor Description
JPasswordField() Constructs a new JPasswordField,
with a default document, null
starting text string, and 0 column
width.
JPasswordField(int columns) Constructs a new empty
JPasswordField with the specified
number of columns.
JPasswordField(String text) Constructs a new JPasswordField
initialized with the specified text.
JPasswordField(String text, int Construct a new JPasswordField
columns) initialized with the specified text
and columns.
Java JPasswordField Example
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
} }
Output:
1
MADHAVI
6
Java Swing
1
MADHAVI
7
Java Swing
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its state
from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
JCheckBox class declaration
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JCheckBox() Creates an initially unselected
check box button with no text, no
icon.
JChechBox(String s) Creates an initially unselected
check box with text.
JCheckBox(String text, boolean Creates a check box with text and
selected) specifies whether or not it is
initially selected.
JCheckBox(Action a) Creates a check box where
properties are taken from the
Action supplied.
Commonly used Methods:
Methods Description
AccessibleContext It is used to get the
getAccessibleContext() AccessibleContext associated
with this JCheckBox.
protected String paramString() It returns a string representation of
this JCheckBox.
Java JCheckBox Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
1
MADHAVI
8
Java Swing
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
1
MADHAVI
9
Java Swing
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample1();
}
}
Output:
2
MADHAVI
0
Java Swing
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample2();
}
}
2
MADHAVI
1
Java Swing
Output:
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam
systems or quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton class declaration
public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JRadioButton() Creates an unselected radio button
with no text.
JRadioButton(String s) Creates an unselected radio button
with specified text.
JRadioButton(String s, boolean Creates a radio button with the
selected) specified text and selected status.
Commonly used Methods:
Methods Description
void setText(String s) It is used to set specified text on
button.
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable
the button.
2
MADHAVI
2
Java Swing
2
MADHAVI
3
Java Swing
2
MADHAVI
4
Java Swing
Java JComboBox
The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu. It inherits
JComponentclass.
JComboBox class declaration
public class JComboBox extends JComponent implements
ItemSelectable, ListDataListener, ActionListener, Accessible
Commonly used Constructors:
Constructor Description
JComboBox() Creates a JComboBox with a
default data model.
JComboBox(Object[] items) Creates a JComboBox that
contains the elements in the
specified array.
JComboBox(Vector<?> items) Creates a JComboBox that
contains the elements in the
specified Vector.
Commonly used Methods:
Methods Description
void addItem(Object anObject) It is used to add an item to the item
list.
void removeItem(Object anObject) It is used to delete an item to the item
list.
void removeAllItems() It is used to remove all the items from
the list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void It is used to add the ActionListener.
addActionListener(ActionListener a)
void addItemListener(ItemListener i) It is used to add the ItemListener.
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
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.
Commonly used Constructors:
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified
columns) data.
Java JTable Example
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
2
MADHAVI
7
Java Swing
2
MADHAVI
8
Java Swing
Java JList
The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or multiple
items. It inherits JComponent class.
JList class declaration
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JList() Creates a JList with an empty,
read-only, model.
JList(ary[] listData) Creates a JList that displays the
elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays
elements from the specified, non-
null, model.
Commonly used Methods:
Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener( notified each time a change to the
selection occurs.
2
MADHAVI
9
Java Swing
ListSelectionListener
listener)
int getSelectedIndex() It is used to return the smallest selected
cell index.
ListModel getModel() It is used to return the data model that
holds a list of items displayed by the JList
component.
void setListData(Object[] It is used to create a read-only ListModel
listData) from an array of objects.
Java JList Example
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[])
{ new ListExample(); }}
Output:
3
MADHAVI
0
Java Swing
{
ListExample1(){
JFrame f= new JFrame();
final JLabel label = new JLabel();
label.setSize(500,100);
JButton b=new JButton("Show");
b.setBounds(200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
final JList<String> list1 = new JList<>(l1);
list1.setBounds(100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
l2.addElement("Turbo C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
final JList<String> list2 = new JList<>(l2);
list2.setBounds(100,200, 75,75);
f.add(list1); f.add(list2); f.add(b); f.add(label);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if (list1.getSelectedIndex() != -1) {
data = "Programming language Selected: " +
list1.getSelectedValue();
label.setText(data);
}
if(list2.getSelectedIndex() != -1){
data += ", FrameWork Selected: ";
for(Object frame :list2.getSelectedValues()){
data += frame + " ";
}
}
3
MADHAVI
1
Java Swing
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample1();
}}
Output:
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as
message dialog box, confirm dialog box and input dialog box. These
dialog boxes are used to display information or get input from the user.
The JOptionPane class inherits JComponent class.
JOptionPane class declaration
public class JOptionPane extends JComponent implements Accessible
Common Constructors of JOptionPane class
Constructor Description
JOptionPane() It is used to create a JOptionPane
with a test message.
JOptionPane(Object message) It is used to create an instance of
JOptionPane to display a
message.
JOptionPane(Object message, int It is used to create an instance of
messageType) JOptionPane to display a message
3
MADHAVI
2
Java Swing
3
MADHAVI
3
Java Swing
3
MADHAVI
4
Java Swing
Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical
scrollbar. It is an implementation of a scrollbar. It inherits JComponent
class.
JScrollBar class declaration
public class JScrollBar extends JComponent implements Adjustable,
Accessible
3
MADHAVI
5
Java Swing
3
MADHAVI
6
Java Swing
3
MADHAVI
7
Java Swing
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample1();
}
}
Output:
Java JPopupMenu
PopupMenu can be dynamically popped up at specific position within a
component. It inherits the JComponent class.
JPopupMenu class declaration
public class JPopupMenu extends JComponent implements Accessible,
MenuElement
4
MADHAVI
0
Java Swing
4
MADHAVI
1
Java Swing
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample1();
}
}
Output:
Java JCheckBoxMenuItem
JCheckBoxMenuItem class represents checkbox which can be included
on a menu. A CheckBoxMenuItem can have text or a graphic icon or
both, associated with it. MenuItem can be selected or deselected.
MenuItems can be configured and controlled by actions.
Nested class
Modifier Class Description
and Type
protected JCheckBoxMenuItem.AccessibleJ This class
class CheckBoxMenuItem implements
accessibility support
for the
JcheckBoxMenuIte
m class.
Constructor
Constructor Description
JCheckBoxMenuItem() It creates an initially unselected
check box menu item with no set
text or icon.
JCheckBoxMenuItem(Action a) It creates a menu item whose
properties are taken from the
Action supplied.
4
MADHAVI
3
Java Swing
4
MADHAVI
4
Java Swing
}
aButton.setText(newLabel);
}
};
caseMenuItem.addActionListener(aListener);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
Output:
Java JSeparator
The object of JSeparator class is used to provide a general purpose
component for implementing divider lines. It is used to draw a line to
separate widgets in a Layout. It inherits JComponent class.
JSeparator class declaration
public class JSeparator extends JComponent implements
SwingConstants, Accessible
Commonly used Constructors of JSeparator
Constructor Description
JSeparator() Creates a new horizontal separator.
JSeparator(int orientation) Creates a new separator with the
specified horizontal or vertical
orientation.
Commonly used Methods of JSeparator
Method Description
void setOrientation(int orientation) It is used to set the orientation of
the separator.
int getOrientation() It is used to return the orientation
of the separator.
Java JSeparator Example 1
import javax.swing.*;
class SeparatorExample
{
4
MADHAVI
6
Java Swing
4
MADHAVI
7
Java Swing
f.add(sep);
JLabel l2 = new JLabel("Below Separator");
f.add(l2);
f.setSize(400, 100);
f.setVisible(true);
}
}
Output:
Java JProgressBar
The JProgressBar class is used to display the progress of the task. It
inherits JComponent class.
JProgressBar class declaration
public class JProgressBar extends JComponent implements
SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JProgressBar() It is used to create a horizontal
progress bar but no string text.
JProgressBar(int min, int max) It is used to create a horizontal
progress bar with the specified
minimum and maximum value.
JProgressBar(int orient) It is used to create a progress bar
with the specified orientation, it can
be either Vertical or Horizontal by
using SwingConstants.VERTICAL
and
SwingConstants.HORIZONTAL
constants.
JProgressBar(int orient, int min, It is used to create a progress bar
int max) with the specified orientation,
minimum and maximum value.
4
MADHAVI
8
Java Swing
Output:
Java JTree
The JTree class is used to display the tree structured data or hierarchical
data. JTree is a complex component. It has a 'root node' at the top most
which is a parent for all nodes in the tree. It inherits JComponent class.
JTree class declaration
public class JTree extends JComponent implements Scrollable,
Accessible
Commonly used Constructors:
Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] value) Creates a JTree with every element of the
specified array as the child of a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as
its root, which displays the root node.
Java JTree Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new
DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new
DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new
DefaultMutableTreeNode("black");
5
MADHAVI
0
Java Swing
DefaultMutableTreeNode green=new
DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:
Java JColorChooser
The JColorChooser class is used to create a color chooser dialog box so
that user can select any color. It inherits JComponent
class.
JColorChooser class declaration
public class JColorChooser extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JColorChooser() It is used to create a color chooser
panel with white color initially.
JColorChooser(color initialcolor) It is used to create a color chooser
panel with the specified color
initially.
Commonly used Methods:
Method Description
void It is used to add a color
addChooserPanel(AbstractColorChooserPanel chooser panel to the
panel) color chooser.
5
MADHAVI
1
Java Swing
5
MADHAVI
2
Java Swing
5
MADHAVI
3
Java Swing
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components
by clicking on a tab with a given title or icon. It inherits JComponent
class.
JTabbedPane class declaration
public class JTabbedPane extends JComponent implements Serializable,
Accessible, SwingConstants
Commonly used Constructors:
Constructor Description
JTabbedPane() Creates an empty TabbedPane
with a default tab placement of
JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane
with a specified tab placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane
tabLayoutPolicy) with a specified tab placement and
tab layout policy.
Java JTabbedPane Example
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
5
MADHAVI
4
Java Swing
new TabbedPaneExample();
}}
Output:
Java JSlider
The Java JSlider class is used to create the slider. By using JSlider, a user
can select a value from a specific range.
Commonly used Constructors of JSlider class
Constructor Description
JSlider() creates a slider with the initial
value of 50 and range of 0 to 100.
JSlider(int orientation) creates a slider with the specified
orientation set by either
JSlider.HORIZONTAL or
JSlider.VERTICAL with the range
0 to 100 and initial value 50.
JSlider(int min, int max) creates a horizontal slider using the
given min and max.
JSlider(int min, int max, int creates a horizontal slider using the
value) given min, max and value.
JSlider(int orientation, int min, int creates a slider using the given
max, int value) orientation, min, max and value.
Commonly used Methods of JSlider class
Method Description
public void is used to set the minor tick
setMinorTickSpacing(int n) spacing to the slider.
public void is used to set the major tick
setMajorTickSpacing(int n) spacing to the slider.
public void setPaintTicks(boolean is used to determine whether tick
b) marks are painted.
public void setPaintLabels(boolean is used to determine whether
b) labels are painted.
public void setPaintTracks(boolean is used to determine whether
b) track is painted.
5
MADHAVI
5
Java Swing
5
MADHAVI
6
Java Swing
Output:
Java JSpinner
The object of JSpinner class is a single line input field that allows the user
to select a number or an object value from an ordered sequence.
JSpinner class declaration
public class JSpinner extends JComponent implements Accessible
Commonly used Contructors:
Constructor Description
JSpinner() It is used to construct a spinner
with an Integer
SpinnerNumberModel with initial
value 0 and no minimum or
maximum limits.
JSpinner(SpinnerModel model) It is used to construct a spinner for
a given model.
Commonly used Methods:
Method Description
void It is used to add a listener to the
addChangeListener(ChangeListener list that is notified each time a
listener) change to the model occurs.
Object getValue() It is used to return the current
value of the model.
Java JSpinner Example
import javax.swing.*;
public class SpinnerExample {
public static void main(String[] args) {
JFrame f=new JFrame("Spinner Example");
SpinnerModel value =
new SpinnerNumberModel(5, //initial value
0, //minimum value
10, //maximum value
1); //step
JSpinner spinner = new JSpinner(value);
spinner.setBounds(100,100,50,30);
f.add(spinner);
f.setSize(300,300);
5
MADHAVI
7
Java Swing
f.setLayout(null);
f.setVisible(true);
}
}
Output:
5
MADHAVI
8
Java Swing
Output:
Java JDialog
The JDialog control represents a top level window with a border and a
title used to take some form of input from the user. It inherits the Dialog
class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
public class JDialog extends Dialog implements WindowConstants,
Accessible, RootPaneContainer
Commonly used Constructors:
Constructor Description
JDialog() It is used to create a modeless
dialog without a title and without
a specified Frame owner.
JDialog(Frame owner) It is used to create a modeless
dialog with specified Frame as its
owner and an empty title.
JDialog(Frame owner, String title, It is used to create a dialog with
boolean modal) the specified title, owner Frame
and modality.
Java JDialog Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
5
MADHAVI
9
Java Swing
Java JPanel
The JPanel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the JComponents
class.
It doesn't have title bar.
JPanel class declaration
public class JPanel extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JPanel() It is used to create a new JPanel
with a double buffer and a flow
layout.
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel
with FlowLayout and the
specified buffering strategy.
6
MADHAVI
0
Java Swing
6
MADHAVI
1
Java Swing
Java JFileChooser
The object of JFileChooser class represents a dialog window from which
the user can select file. It inherits JComponent class.
JFileChooser class declaration
public class JFileChooser extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JFileChooser() Constructs a JFileChooser pointing to the
user's default directory.
JFileChooser(File Constructs a JFileChooser using the given
currentDirectory) File as the path.
JFileChooser(String Constructs a JFileChooser using the given
currentDirectoryPath) path.
Java JFileChooser Example
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements
ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
6
MADHAVI
2
Java Swing
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
}
}
}
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to
switch on or off.
Nested Classes
Modifier Class Description
and Type
protected JToggleButton.AccessibleJToggleButton This class
class implements
accessibility
support for the
6
MADHAVI
3
Java Swing
JToggleButton
class.
static class JToggleButton.ToggleButtonModel The
ToggleButton
model
Constructors
Constructor Description
JToggleButton() It creates an initially unselected
toggle button without setting the
text or image.
JToggleButton(Action a) It creates a toggle button where
properties are taken from the
Action supplied.
JToggleButton(Icon icon) It creates an initially unselected
toggle button with the specified
image but no text.
JToggleButton(Icon icon, boolean It creates a toggle button with the
selected) specified image and selection
state, but no text.
JToggleButton(String text) It creates an unselected toggle
button with the specified text.
JToggleButton(String text, boolean It creates a toggle button with the
selected) specified text and selection state.
JToggleButton(String text, Icon It creates a toggle button that has
icon) the specified text and image, and
that is initially unselected.
JToggleButton(String text, Icon It creates a toggle button with the
icon, boolean selected) specified text, image, and
selection state.
Methods
6
MADHAVI
4
Java Swing
6
MADHAVI
5
Java Swing
Output
Java JToolBar
JToolBar container allows us to group other components, usually buttons
with icons in a row or column. JToolBar provides a component which is
useful for displaying commonly used actions or controls.
Nested Classes
Modifier and Class Description
Type
protected class JToolBar.AccessibleJToolBar This class
implements
accessibility
support for the
JToolBar class.
static class JToolBar.Separator A toolbar-specific
separator.
Constructors
Constructor Description
JToolBar() It creates a new tool bar;
orientation defaults to
HORIZONTAL.
JToolBar(int orientation) It creates a new tool bar with the
specified orientation.
JToolBar(String name) It creates a new tool bar with the
specified name.
JToolBar(String name, int It creates a new tool bar with a
orientation) specified name and orientation.
Useful Methods
Modifier and Type Method Description
JButton add(Action a) It adds a new JButton
which dispatches the
action.
protected void addImpl(Compone If a JButton is being added,
nt comp, Object it is initially set to be
constraints, int disabled.
index)
6
MADHAVI
6
Java Swing
6
MADHAVI
7
Java Swing
Java JViewport
The JViewport class is used to implement scrolling. JViewport is
designed to support both logical scrolling and pixel-based scrolling. The
viewport's child, called the view, is scrolled by calling the
JViewport.setViewPosition() method.
Nested Classes
Modifier and Class Description
Type
protected class JViewport.AccessibleJViewport This class
implements
accessibility
support for the
Jviewport class.
protected class JViewport.ViewListener A listener for the
view.
6
MADHAVI
8
Java Swing
Fields
Modifier Field Description
and Type
static int BACKINGSTORE_SCROLL_MODE It draws viewport
contents into an
offscreen image.
protected backingStoreImage The view image
Image used for a backing
store.
static int BLIT_SCROLL_MODE It uses
graphics.copyArea
to implement
scrolling.
protected isViewSizeSet True when the
boolean viewport
dimensions have
been determined.
protected lastPaintPosition The last
Point viewPosition that
we've painted, so
we know how
much of the
backing store
image is valid.
protected scrollUnderway The
boolean scrollUnderway
flag is used for
components like
JList.
static int SIMPLE_SCROLL_MODE This mode uses
the very simple
method of
redrawing the
entire contents of
the scrollpane each
time it is scrolled.
6
MADHAVI
9
Java Swing
Constructor
Constructor Description
JViewport() Creates a JViewport.
Methods
Modifier and Type Method Description
void addChangeListener(ChangeList It adds a
ener l) ChangeListen
er to the list
that is
notified each
time the
view's size,
position, or
the viewport's
extent size
has changed.
protected createLayoutManager() Subclassers
LayoutManager can override
this to install
a different
layout
manager (or
null) in the
constructor.
protected createViewListener() It creates a
Jviewport.ViewListe listener for
ner the view.
int getScrollMode() It returns the
current
scrolling
mode.
Component getView() It returns the
JViewport's
one child or
null.
Point getViewPosition() It returns the
view
coordinates
that appear in
the upper left
hand corner
7
MADHAVI
0
Java Swing
of the
viewport, or
0,0 if there's
no view.
Dimension getViewSize() If the view's
size hasn't
been
explicitly set,
return the
preferred
size,
otherwise
return the
view's current
size.
void setExtentSize(Dimension It sets the size
newExtent) of the visible
part of the
view using
view
coordinates.
void setScrollMode(int mode) It used to
control the
method of
scrolling the
viewport
contents.
void setViewSize(Dimension It sets the size
newSize) of the view.
JViewport Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
public class ViewPortClass2 {
public static void main(String[] args) {
JFrame frame = new JFrame("Tabbed Pane Sample");
7
MADHAVI
1
Java Swing
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton jButton1 = new JButton();
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_S
CROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
jScrollPane.getViewport().add(jButton1, null);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
Output:
Java JFrame
The javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
Modifier and Type Class Description
protected class JFrame.AccessibleJFrame This class
implements
accessibility support
for the JFrame class.
7
MADHAVI
2
Java Swing
Fields
Modifier and Type Field Description
protected accessibleContext The accessible
AccessibleContext context property.
static int EXIT_ON_CLOSE The exit
application default
window close
operation.
protected JRootPane rootPane The JRootPane
instance that
manages the
contentPane and
optional menuBar
for this frame, as
well as the
glassPane.
protected boolean rootPaneCheckingEnabled If true then calls to
add and setLayout
will be forwarded
to the contentPane.
Constructors
Constructor Description
JFrame() It constructs a new frame that is
initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a
screen device and a blank title.
JFrame(String title) It creates a new, initially invisible
Frame with the specified title.
JFrame(String title, It creates a JFrame with the
GraphicsConfiguration gc) specified title and the specified
GraphicsConfiguration of a
screen device.
Useful Methods
Modifier Method Description
and Type
protected addImpl(Component comp, Object Adds the specified
void constraints, int index) child Component.
protected createRootPane() Called by the
JRootPane constructor methods
7
MADHAVI
3
Java Swing
7
MADHAVI
4
Java Swing
Java JLayeredPane
The JLayeredPane class is used to add depth to swing container. It is used
to provide a third dimension for positioning component and divide the
depth-range into several different layers.
JLayeredPane class declaration
public class JLayeredPane extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JLayeredPane It is used to create a new
JLayeredPane
Commonly used Methods:
Method Description
int getIndexOf(Component c) It is used to return the index of the
specified Component.
int getLayer(Component c) It is used to return the layer attribute
for the specified Component.
int getPosition(Component c) It is used to return the relative
position of the component within its
layer.
7
MADHAVI
5
Java Swing
7
MADHAVI
6
Java Swing
Java JDesktopPane
The JDesktopPane class, can be used to create "multi-document"
applications. A multi-document application can have many windows
included in it. We do it by making the contentPane in the main window as
an instance of the JDesktopPane class or a subclass. Internal windows add
instances of JInternalFrame to the JdesktopPane instance. The internal
windows are the instances of JInternalFrame or its subclasses.
Fields
Modifier and Type Field Description
static int LIVE_DRAG_MODE It indicates that the
entire contents of
the item being
dragged should
appear inside the
desktop pane.
static int OUTLINE_DRAG_MODE It indicates that an
outline only of the
item being dragged
should appear inside
the desktop pane.
Constructor
Constructor Description
JDesktopPane() Creates a new JDesktopPane.
Java JDesktopPane Example
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
public class JDPaneDemo extends JFrame
{
public JDPaneDemo()
{
CustomDesktopPane desktopPane = new CustomDesktopPane();
Container contentPane = getContentPane();
contentPane.add(desktopPane, BorderLayout.CENTER);
desktopPane.display(desktopPane);
setTitle("JDesktopPane Example");
setSize(300,350);
7
MADHAVI
7
Java Swing
setVisible(true);
}
public static void main(String args[])
{
new JDPaneDemo();
}
}
class CustomDesktopPane extends JDesktopPane
{
int numFrames = 3, x = 30, y = 30;
public void display(CustomDesktopPane dp)
{
for(int i = 0; i < numFrames ; ++i )
{
JInternalFrame jframe = new JInternalFrame("Internal Frame " + i ,
true, true, true, true);
jframe.setBounds(x, y, 250, 85);
Container c1 = jframe.getContentPane( ) ;
c1.add(new JLabel("I love my country"));
dp.add( jframe );
jframe.setVisible(true);
y += 85;
}
}
}
Output:
7
MADHAVI
8
Java Swing
Java JEditorPane
JEditorPane class is used to create a simple text editor window. This class
has setContentType() and setText() methods.
setContentType("text/plain"): This method is used to set the content type
to be plain text.
setText(text): This method is used to set the initial text content.
Nested Classes
Modi Class Description
fier
and
Type
prote JEditorPane.AccessibleJEditorP This class implements
cted ane accessibility support for the
class JEditorPane class.
prote JEditorPane.AccessibleJEditorP This class provides support
cted aneHTML for AccessibleHypertext, and
class is used in instances where the
EditorKit installed in this
JEditorPane is an instance of
HTMLEditorKit.
prote JEditorPane.JEditorPaneAccessi What's returned by
cted bleHypertextSupport AccessibleJEditorPaneHTM
class L.getAccessibleText
Fields
Modifier and Field Description
Type
static String HONOR_DISPLAY_PRO Key for a client property
PERTIES used to indicate whether
the default font and
foreground color from
the component are used
if a font or foreground
color is not specified in
the styled text.
static String W3C_LENGTH_UNITS Key for a client property
used to indicate whether
w3c compliant length
units are used for html
rendering.
7
MADHAVI
9
Java Swing
Constructors
Constructor Description
JEditorPane() It creates a new JEditorPane.
JEditorPane(String url) It creates a JEditorPane based on
a string containing a URL
specification.
JEditorPane(String type, String It creates a JEditorPane that has
text) been initialized to the given text.
JEditorPane(URL initialPage) It creates a JEditorPane based on
a specified URL for input.
Useful Methods
Modifier Method Description
and Type
void addHyperlinkListener(Hyp Adds a hyperlink listener for
erlinkListener listener) notification of any changes,
for example when a link is
selected and entered.
protected createDefaultEditorKit() It creates the default editor kit
EditorKit (PlainEditorKit) for when the
component is first created.
void setText(String t) It sets the text of this
TextComponent to the
specified content, which is
expected to be in the format
of the content type of this
editor.
void setContentType(String It sets the type of content that
type) this editor handles.
void setPage(URL page) It sets the current URL being
displayed.
void read(InputStream in, This method initializes from a
Object desc) stream.
void scrollToReference(String It scrolls the view to the given
reference) reference location (that is, the
value returned by the
UL.getRef method for the
URL being displayed).
void setText(String t) It sets the text of this
TextComponent to the
specified content, which is
expected to be in the format
8
MADHAVI
0
Java Swing
8
MADHAVI
1
Java Swing
Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When
screen size is limited, we use a scroll pane to display a large component
or a component whose size can change dynamically.
8
MADHAVI
2
Java Swing
Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The
JScrollPane(Component) Component parameter, when
JScrollPane(int, int) present, sets the scroll pane's
JScrollPane(Component, int, int) client. The two int parameters,
when present, set the vertical and
horizontal scroll bar policies
(respectively).
Useful Methods
Modifier Method Description
void setColumnHeaderView(C It sets the column header for
omponent) the scroll pane.
void setRowHeaderView(Com It sets the row header for the
ponent) scroll pane.
void setCorner(String, It sets or gets the specified
Component) corner. The int parameter
Compon getCorner(String) specifies which corner and
ent must be one of the following
constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNE
R,
LOWER_TRAILING_CORNE
R,
UPPER_LEADING_CORNER
,
UPPER_TRAILING_CORNE
R.
void setViewportView(Compo Set the scroll pane's client.
nent)
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.*;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
8
MADHAVI
3
Java Swing
8
MADHAVI
4
Java Swing
Java JSplitPane
JSplitPane is used to divide two components. The two components are
divided based on the look and feel implementation, and they can be
resized by the user. If the minimum size of the two components is greater
than the size of the split pane, the divider will not allow you to resize it.
The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using
JSplitPane.VERTICAL_SPLIT. When the user is resizing the
components the minimum size of the components is used to determine the
maximum/minimum position the components can be set to.
Constructors
Constructor Description
JSplitPane() It creates a new JsplitPane
configured to arrange the child
components side-by-side
horizontally, using two buttons
for the components.
JSplitPane(int newOrientation) It creates a new JsplitPane
configured with the specified
orientation.
JSplitPane(int newOrientation, It creates a new JsplitPane with
boolean newContinuousLayout) the specified orientation and
redrawing style.
JSplitPane(int newOrientation, It creates a new JsplitPane with
boolean newContinuousLayout, the specified orientation and
Component newLeftComponent, redrawing style, and with the
Component newRightComponent) specified components.
JSplitPane(int newOrientation, It creates a new JsplitPane with
Component newLeftComponent, the specified orientation and the
Component newRightComponent) specified components.
Useful Methods
Modifier and Type Method Description
protected void addImpl(Component It cdds the specified
comp, Object constraints, component to this split
int index) pane.
AccessibleContext It gets the
getAccessibleCont AccessibleContext
ext() associated with this
JSplitPane.
8
MADHAVI
5
Java Swing
8
MADHAVI
6
Java Swing
Java JTextPane
JTextPane is a subclass of JEditorPane class. JTextPane is used for styled
document with embedded images and components. It is text component
that can be marked up with attributes that are represented graphically.
JTextPane uses a DefaultStyledDocument as its default model.
8
MADHAVI
7
Java Swing
Constructors
Constructor Description
JTextPane() It creates a new JTextPane.
JtextPane(StyledDocument doc) It creates a new JTextPane, with
a specified document model.
Useful Methods
Modifier and Type Method Description
Style addStyle(String nm, Style It adds a new style into the
parent) logical style hierarchy.
AttributeSet getCharacterAttributes() It fetches the character
attributes in effect at the
current location of the caret, or
null.
StyledDocument It fetches the model associated
getStyledDocument() with the editor.
void setDocument(Document doc) It associates the editor with a
text document.
void It applies the given attributes
setCharacterAttributes(Attribute to character content.
Set attr, boolean replace)
void removeStyle(String nm) It removes a named non-null
style previously added to the
document.
void setEditorKit(EditorKit kit) It sets the currently installed
kit for handling content.
void It associates the editor
setStyledDocument(StyledDocu with a text document.
ment doc)
JTextPane Example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneExample {
public static void main(String args[]) throws BadLocationException {
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
JTextPane pane = new JTextPane();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setBold(attributeSet, true);
8
MADHAVI
8
Java Swing
Java JRootPane
JRootPane is a lightweight container used behind the scenes by JFrame,
JDialog, JWindow, JApplet, and JInternalFrame.
Constructor
Constructor Description
JRootPane() Creates a JRootPane, setting up its glassPane, layeredPane, and
contentPane.
Useful Methods
Modifier and Type Method Description
protected void Overridden to enforce the position of
addImpl(Component comp, the glass component as the zero child.
Object constraints, int index)
8
MADHAVI
9
Java Swing
9
MADHAVI
0
Java Swing
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
9
MADHAVI
2
Java Swing
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[]){
new IconExample();
}
}
Output:
9
MADHAVI
3
Java Swing
t = new Thread(this);
t.start();
b=new JButton();
b.setBounds(100,100,100,50);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
printTime();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}
9
MADHAVI
4
Java Swing
9
MADHAVI
5
Java Swing
9
MADHAVI
6
Java Swing
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
}
Output:
}
public static void main(String[] args) {
MyCanvas m=new MyCanvas();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
f.setVisible(true);
}
}
Output:
9
MADHAVI
8