Java Swing Tutorial
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
There are many differences between
java awt and swing that are given below.
No. |
Java AWT |
Java Swing |
1) |
AWT components are platform-dependent. |
Java swing components are platform-independent. |
2) |
AWT components are heavyweight. |
Swing components are lightweight. |
3) |
AWT doesn't support pluggable look and feel. |
Swing supports pluggable look and feel. |
4) |
AWT provides less components than Swing. |
Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane etc. |
5) |
AWT doesn't follows MVC(Model View Controller)
where model represents data, view represents presentation and controller acts
as an interface between model and view. |
Swing follows MVC. |
What
is JFC
The Java Foundation Classes (JFC)
are a set of GUI components which simplify the development of desktop
applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given
below.
Method |
Description |
public
void add(Component c) |
add a
component on another component. |
public
void setSize(int width,int height) |
sets
size of the component. |
public
void setLayout(LayoutManager m) |
sets the
layout manager for the component. |
public
void setVisible(boolean b) |
sets the
visibility of the component. It is by default false. |
Java Swing Examples
There are two ways to create a frame:
- By creating the object of Frame
class (association)
- By extending Frame class
(inheritance)
We can write the code of swing inside the main(), constructor or any other
method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding
it on the JFrame object inside the main() method.
import
javax.swing.*;
public class
FirstSwingExample {
public static void
main(String[] args) {
JFrame f=new
JFrame();
JButton b=new
JButton("click");
b.setBounds(130,100,100, 40);
f .add(b);
f.setSize(400,500);
f.setLayout(null);
f.setVisible(true);
}
}
Example of Swing by Association inside constructor
We can
also write all the codes of creating JFrame, JButton and method call inside the
java constructor.
import
javax.swing.*;
public class
Simple {
JFrame f;
Simple(){
f=new
JFrame();
JButton b=new
JButton("click");
b.setBounds(130,100,100, 40);
f.add(b);
f.setSize(400,500);
f.setLayout(null);
f.setVisible(true);
}
public static void
main(String[] args) {
new
Simple();
}
}
Simple
example of Swing by inheritance
We can
also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.
File:
Simple2.java
import
javax.swing.*;
public class Simple2
extends JFrame{
JFrame f;
Simple2(){
JButton b=new
JButton("click");
b.setBounds(130,100,100, 40);
add(b);//adding button on
frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void
main(String[] args) {
new
Simple2();
}}
Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
- public class JButton extends AbstractButton implements Accessible
Java JButton Example
import
javax.swing.*;
public class
Simple2 {
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);
}
}
Java JButton Example with
ActionListener
import
java.awt.event.*;
import
javax.swing.*;
public class
Simple2 {
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);
}
}
Example of displaying
image on the button:
public class ButtonExample{
ButtonExample(){
JFrame f=new
JFrame("Button Example");
JButton b=new
JButton(new ImageIcon("G:\\buttonn.jpg"));
b.setBounds(100,100,100,
100);
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();
}
}
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
Let's see the declaration for javax.swing.JLabel class.
- public class JLabel extends JComponent implements SwingConstants, Accessible
Java JLabel Example
import
javax.swing.*;
public class
LabelExample
{
public static void
main(String args[])
{
JFrame f= new
JFrame("Label Example");
JLabel l1,l2;
l1=new
JLabel("First Label.");
l1.setBounds(50,50,
100,30);
l2=new
JLabel("Second Label.");
l2.setBounds(50,100,
100,30);
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
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();
l.setText("IP
of "+host+" is: "+ip);
}catch(Exception
ex){System.out.println(ex);}
}
public static void
main(String[] args) {
new
LabelExample();
} }
Java JTextField
The object of a JTextField class is a text component that allows the editing
of a single line text. It inherits JTextComponent class.
JTextField class
declaration
Let's see the declaration for javax.swing.JTextField class.
- public class JTextField extends JTextComponent implements SwingConstants
Java JTextField Example
import javax.swing.*;
public class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new
JFrame("TextField Example");
JTextField t1,t2;
t1=new
JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100,
200,30);
t2=new
JTextField("AWT Tutorial");
t2.setBounds(50,150,
200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField Example
with ActionListener
import
javax.swing.*;
import
java.awt.event.*;
public class
TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new
JFrame();
tf1=new
JTextField();
tf1.setBounds(50,50,150,20);
tf2=new
JTextField();
tf2.setBounds(50,100,150,20);
tf3=new
JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new
JButton("+");
b1.setBounds(50,200,50,50);
b2=new
JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void
actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int
a=Integer.parseInt(s1);
int
b=Integer.parseInt(s2);
int
c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String
result=String.valueOf(c);
tf3.setText(result);
}
public static void
main(String[] args) {
new
TextFieldExample();
} }
Java JTextArea
The object of a JTextArea class is a multi line region that displays text.
It allows the editing of multiple line text. It inherits JTextComponent class
JTextArea class
declaration
Let's see the declaration for javax.swing.JTextArea class.
- public class JTextArea extends JTextComponent
Java JTextArea Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new
JFrame();
JTextArea area=new
JTextArea("Welcome to java");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new
TextAreaExample();
}}
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);
}
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();
}
}
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
Let's see the declaration for javax.swing.JPasswordField class.
- public class JPasswordField extends JTextField
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);
}
}
Java JPasswordField
Example with ActionListener
import
javax.swing.*;
import
java.awt.event.*;
public class
PasswordFieldExample {
public static void
main(String[] args) {
JFrame f=new
JFrame("Password Field Example");
final
JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final
JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JLabel l1=new
JLabel("Username:");
l1.setBounds(20,20, 80,30);
JLabel l2=new
JLabel("Password:");
l2.setBounds(20,75, 80,30);
JButton b = new
JButton("Login");
b.setBounds(100,120, 80,30);
final
JTextField text = new JTextField();
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b);
f.add(text);
f.setSize(300,300);
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);
}
});
}
}
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its state from
"on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class
declaration
Let's see the declaration for javax.swing.JCheckBox class.
- public class JCheckBox extends JToggleButton implements Accessible
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);
f.setVisible(true);
}
public static void
main(String args[])
{
new
CheckBoxExample();
}}
Java JCheckBox Example
with ItemListener
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new
JFrame("CheckBox Example");
final
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1
= new JCheckBox("C++");
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();
}
}
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);
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();
}
}
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam systems or
quiz.
It should be added in ButtonGroup to select one radio button only.
JRadioButton class
declaration
Let's see the declaration for javax.swing.JRadioButton class.
- public class JRadioButton extends JToggleButton implements Accessible
Java JRadioButton Example
import
javax.swing.*;
public class
RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new
JFrame();
JRadioButton r1=new
JRadioButton("A) Male");
JRadioButton r2=new
JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new
ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void
main(String[] args) {
new
RadioButtonExample();
}
}
Java JRadioButton Example
with ActionListener
import
javax.swing.*;
import
java.awt.event.*;
class RadioButtonExample
extends JFrame implements
ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new
JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new
JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new
ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new
JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void
actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You
are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You
are Female.");
}
}
public static void
main(String args[]){
new
RadioButtonExample();
}}
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits JComponent class.
JComboBox class
declaration
Let's see the declaration for javax.swing.JComboBox class.
- public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, Accessible
Java JComboBox Example
import
javax.swing.*;
public class
ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new
JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new
JComboBox(country);
cb.setBounds(50,
50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void
main(String[] args) {
new
ComboBoxExample();
}
}
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) {
String data = "Programming
language Selected: "
+
cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void
main(String[] args) {
new
ComboBoxExample();
}
}
Java JTable
The JTable class is used to display data in tabular form. It is composed of
rows and columns.
JTable class declaration
Let's see the declaration for javax.swing.JTable class.
Java JTable Example
import
javax.swing.*;
public class
TableExample {
JFrame f;
TableExample(){
f=new
JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"103","Sachin","700000"},
{"104","Sachin","700000"},
{"105","Sachin","700000"},
{"106","Sachin","700000"},
{"107","Sachin","700000"},
{"108","Sachin","700000"},
{"109","Sachin","700000"},
{"110","Sachin","700000"},
{"111","Sachin","700000"},
{"112","Sachin","700000"},
{"113","Sachin","700000"},
{"114","Sachin","700000"},
{"115","Sachin","700000"},
{"116","Sachin","700000"},
{"117","Sachin","700000"},
{"118","Sachin","700000"},
{"119","Sachin","700000"},
{"120","Sachin","700000"},
{"121","Sachin","700000"},
{"122","Sachin","700000"},
{"101","Sachin","700000"},
{"101","Sachin","700000"},
};
String column[]={"ID","NAME","SALARY"};
JTable jt=new
JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new
JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void
main(String[] args) {
new
TableExample();
}
}
Java JList
The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or multiple
items. It inherits JComponent class.
JList class declaration
Let's see the declaration for javax.swing.JList class.
- public class JList extends JComponent implements Scrollable,
Java JList Example
import
javax.swing.*;
public class
ListExample
{
ListExample(){
JFrame f= new
JFrame();
DefaultListModel
l1 = new DefaultListModel();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList 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();
}}
Java JList Example with ActionListener
import
javax.swing.*;
import
java.awt.event.*;
public class
ListExample
{
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 l1 = new DefaultListModel();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
final JList
list1 = new JList(l1);
list1.setBounds(100,100, 75,75);
DefaultListModel l2 = new
DefaultListModel();
l2.addElement("Turbo
C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
final JList
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 + " ";
}
}
label.setText(data);
}
});
}
public static void
main(String args[])
{
new
ListExample();
}}
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
Let's see the declaration for javax.swing.JScrollBar class.
- public class JScrollBar extends JComponent implements Adjustable, Accessible
Java JScrollBar Example
import
javax.swing.*;
public class
ScrollBarExample
{
ScrollBarExample(){
JFrame f= new
JFrame("Scrollbar Example");
JScrollBar s=new
JScrollBar();
s.setBounds(100,100,
50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void
main(String args[])
{
new
ScrollBarExample();
}}
Java JScrollBar Example
with AdjustmentListener
import
javax.swing.*;
import
java.awt.event.*;
class
ScrollBarExample
{
ScrollBarExample(){
JFrame f= new
JFrame("Scrollbar Example");
final
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
final
JScrollBar s=new JScrollBar();
s.setBounds(100,100,
50,100);
f.add(s);
f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
s.addAdjustmentListener(new
AdjustmentListener() {
public void
adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical
Scrollbar value is:"+ s.getValue());
}
});
}
public static void
main(String args[])
{
new
ScrollBarExample();
}}
Java JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to
display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull
down menu component which is displayed from the menu bar. It inherits the
JMenuItem class.
The object of JMenuItem class adds a
simple labeled menu item. The items used in a menu must belong to the JMenuItem
or any of its subclass.
JMenuBar
class declaration
- public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu
class declaration
- public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem
class declaration
- public class JMenuItem extends AbstractButton implements Accessible, MenuElement
Java JMenuItem and JMenu
Example
import
javax.swing.*;
public class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new
JFrame("Menu and MenuItem Example");
JMenuBar mb=new
JMenuBar();
menu=new
JMenu("Menu");
submenu=new
JMenu("Sub Menu");
i1=new
JMenuItem("Item 1");
i2=new
JMenuItem("Item 2");
i3=new
JMenuItem("Item 3");
i4=new
JMenuItem("Item 4");
i5=new
JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void
main(String args[])
{
new MenuExample();
}}
Java JProgressBar
The JProgressBar class is used to display the progress of the task. It
inherits JComponent class.
JProgressBar class
declaration
Let's see the declaration for javax.swing.JProgressBar class.
- public class JProgressBar extends JComponent implements SwingConstants, Accessible
Java JProgressBar Example
import
javax.swing.*;
public class ProgressBarExample
extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample(){
jb=new
JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void
iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception
e){}
}
}
public static void
main(String[] args) {
ProgressBarExample
m=new ProgressBarExample();
m.setVisible(true);
m.iterate();
}
}
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
Let's see the declaration for javax.swing.JTree class.
- public class JTree extends JComponent implements Scrollable, Accessible
Java JTree Example
import
javax.swing.*;
import
javax.swing.tree.DefaultMutableTreeNode;
public class
TreeExample {
JFrame
f;
TreeExample(){
f=new
JFrame();
DefaultMutableTreeNode style=new
DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new
DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new
DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new
DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new
DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new
DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new
DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black);
color.add(green);
JTree
jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public
static void main(String[] args) {
new
TreeExample();
}}
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by
clicking on a tab with a given title or icon. It inherits JComponent class.
JTabbedPane class
declaration
Let's see the declaration for javax.swing.JTabbedPane class.
- public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants
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) {
new
TabbedPaneExample();
}}
Java JSpinner
The object of JSpinner class is a single line input field that allows the
user to select a number or an object value from an ordered sequence.
JSpinner class
declaration
Let's see the declaration for javax.swing.JSpinner class.
- public class JSpinner extends JComponent implements Accessible
import
javax.swing.*;
public class
SpinnerExample {
public static void
main(String[] args) {
JFrame f=new
JFrame("Spinner Example");
SpinnerModel value =new
SpinnerNumberModel(5, 0, 10,1);
JSpinner spinner = new
JSpinner(value);
spinner.setBounds(100,100,50,30);
f.add(spinner);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
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.
import
java.awt.FlowLayout;
import
javax.swing.JFrame;
import
javax.swing.JScrollPane;
import
javax.swing.JTextArea;
public class
JScrollPaneExample {
private static final long serialVersionUID =
1L;
private static void
createAndShowGUI() {
//
Create and set up the window.
final
JFrame frame = new JFrame("Scroll Pane Example");
//
Display the window.
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
set flow layout for the frame
frame.getContentPane().setLayout(new
FlowLayout());
JTextArea
textArea = new JTextArea(20, 20);
JScrollPane
scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void
main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new
Runnable() {
public void run()
{
createAndShowGUI();
}
});
}
}
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.
JSplitPane Example
import
java.awt.FlowLayout;
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, panel2);
//
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
//
panel1, panel2);
frame.getContentPane().add(splitPane);
}
public
static void main(String[] args) {
//
Schedule a job for the event-dispatching thread:
//
creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShow();
}
});
}
}
Java
LayoutManagers
The LayoutManagers are used to
arrange components in a particular manner. LayoutManager is an interface that
is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:
- java.awt.BorderLayout
- java.awt.FlowLayout
- java.awt.GridLayout
- java.awt.CardLayout
- java.awt.GridBagLayout
- javax.swing.BoxLayout
- javax.swing.GroupLayout
- javax.swing.ScrollPaneLayout
- javax.swing.SpringLayout etc
Java
BorderLayout
The BorderLayout is used to arrange
the components in five regions: north, south, east, west and center. Each
region (area) may contain one component only. It is the default layout of frame
or window. The BorderLayout provides five constants for each region:
- public static final int NORTH
- public static final int SOUTH
- public static final int EAST
- public static final int WEST
- public static final int CENTER
Example
of BorderLayout class:
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new
JButton("NORTH");
JButton b2=new
JButton("SOUTH");
JButton b3=new
JButton("EAST");
JButton b4=new
JButton("WEST");
JButton b5=new
JButton("CENTER");
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Java GridLayout
The GridLayout is used to arrange
the components in rectangular grid. One component is displayed in each
rectangle.
Example
of GridLayout class
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new
JFrame();
JButton b1=new
JButton("1");
JButton b2=new
JButton("2");
JButton b3=new
JButton("3");
JButton b4=new
JButton("4");
JButton b5=new
JButton("5");
JButton b6=new
JButton("6");
JButton b7=new
JButton("7");
JButton b8=new
JButton("8");
JButton b9=new
JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new
GridLayout(3,3));
//setting grid
layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new
MyGridLayout();
}
}
Java FlowLayout
The FlowLayout is used to arrange
the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
Fields
of FlowLayout class
- public static final int LEFT
- public static final int RIGHT
- public static final int CENTER
- public static final int LEADING
- public static final int TRAILING
Example
of FlowLayout class
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new
JFrame();
JButton b1=new
JButton("1");
JButton b2=new
JButton("2");
JButton b3=new
JButton("3");
JButton b4=new
JButton("4");
JButton b5=new
JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new
FlowLayout(FlowLayout.RIGHT));
//setting flow
layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new
MyFlowLayout();
}
}
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or
horizontally. For this purpose, BoxLayout provides four constants. They are as
follows:
Note: BoxLayout class is
found in javax.swing package.
Fields of BoxLayout class
- public
static final int X_AXIS
- public
static final int Y_AXIS
- public
static final int LINE_AXIS
- public
static final int PAGE_AXIS
Example
of BoxLayout class with Y-AXIS:
import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame
{
Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button
" + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this,
BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String
args[]){
BoxLayoutExample1 b=new
BoxLayoutExample1();
}
}
Java CardLayout
The CardLayout class manages the
components in such a manner that only one component is visible at a time. It
treats each component as a card that is why it is known as CardLayout.
Example
of CardLayout class
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public class CardLayoutExample
extends JFrame implements
ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new
CardLayout();
//create
CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new
JButton("Apple");
b2=new
JButton("Boy");
b3=new
JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void
actionPerformed(ActionEvent e) {
card.next(c);
}
public static void
main(String[] args) {
CardLayoutExample cl=new
CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Comments
Post a Comment