Java Notes 8
Java Notes 8
Java Swing
by Debasis Samanta
CONTENTS
• Introduction
• AWT versus Swing
• Swing in depth
• Practice Questions
• Assignment
• Q&A
Introduction
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. Java Swing provides better lightweight components than AWT. The javax.swing package
provides classes for Java Swing components such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Swing in depth
Hierarchy of Java Swing classes:
Figure 10.2 :Hierarchy of Java Swing classes
Commonly used methods in Component class:
Illustration 10.1
// A program to add a label and button in a frame
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);
}
}
Illustration 10.2
// A program to add panel to GUI
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample() {
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1);
panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new PanelExample();
}
}
We can also write all the codes of creating JFrame, JButton and method call inside the Java
constructor.
Illustration 10.3
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
//creating instance of JFrame
JFrame f=new JFrame();
//creating instance of JButton
JButton b=new JButton("click");
//x axis, y axis, width, height
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
}
}
Illustration 10.4
// 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();
}
}
Illustration 10.5
// inherit the JFrame class, so there is no need to create the instance of JFrame
class explicitly.
import javax.swing.*;
//inheriting JFrame
public class Simple2 extends JFrame{
JFrame f;
Simple2(){
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);
add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}
}
Illustration 10.7
// Button with image
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();
}
}
Illustration 10.8
import javax.swing.*;
class LabelExample
{
public static void main(String args[]){
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Illustration 10.9
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
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();
}
}
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();
}
}
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 Swing 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 JCheckBox changes its state from "on" to "off" or
from "off" to "on ".It inherits JToggleButton class.
Below is the declaration for javax.swing.JCheckBox
class. public�class�JCheckBox�extends�JToggleButton�implements�Accessible�
�
Class JCheckBox : Constructors:
Illustration 10.13
// A program to show use of CheckBox
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 Swing 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.
Illustration 10.14
// A program to show use of RadioButton
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 Swing 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.
Below is the declaration for javax.swing.JComboBox
class. public�class�JComboBox�extends�JComponent�implements�ItemSelectable,
�ListDataListener,�ActionListener,�Accessible����
Class JComboBox : Constructors:
Illustration 10.15
// A program to show use of ComboBox
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 Swing JTable: The JTable class is used to display data in tabular form. It is composed of
rows and columns
Class JTable : Constructors:
Illustration 10.16
// A program to create a table and show some data
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);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java Swing 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.
Illustration 10.17
// A program to create a list and list some data
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 Swing 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.
Illustration 10.18
// A program to show some info to using JOptionPane
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to IIT Kharagpur.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Java Swing 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.
Illustration 10.19
import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}
Java Swing JMenuBar: The JMenuBar class is used to display menu bar on the window or
frame. It may have several menus.
Illustration 10.20
// A program to create a menu bar and show menu items
import javax.swing.*;
class MenuExample{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");i4=new JMenuItem("Item 4");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4);
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();
}
}
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();
}}
Java Swing JCheckBoxMenuItem: JCheckBoxMenuItem class represents checkbox which can
be included on a menu. A JCheckBoxMenuItem 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.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JavaCheckBoxMenuItemExample {
public static void main(final String args[]) {
JFrame frame = new JFrame("Jmenu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem menuItem1 = new JMenuItem("Open", KeyEvent.VK_N);
fileMenu.add(menuItem1);
JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem("Option_1");
caseMenuItem.setMnemonic(KeyEvent.VK_C);
fileMenu.add(caseMenuItem);
ActionListener aListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
AbstractButton aButton = (AbstractButton) event.getSource();
boolean selected = aButton.getModel().isSelected();
String newLabel;
Icon newIcon;
if (selected) {
newLabel = "Value-1";
} else {
newLabel = "Value-2";
}
aButton.setText(newLabel);
}
};
caseMenuItem.addActionListener(aListener);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
Java Swing 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.
Illustration 10.23
import javax.swing.*;
class SeparatorExample{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
SeparatorExample() {
JFrame f = new JFrame("Separator Example");
JMenuBar mb = new JMenuBar();
menu = new JMenu("Menu");
i1 = new JMenuItem("Item 1");
i2 = new JMenuItem("Item 2");
menu.add(i1);
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();
}}
Java Swing JProgressBar: The JProgressBar class is used to display the progress of the task.
It inherits JComponent class.
Illustration 10.24
// A program to show progress bar
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 Swing 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.
Below is the declaration for javax.swing.JTree
class. public�class��JTree�extends�JComponent�implements�Scrollable,�Access
ible�
Class JTree : Constructors:
Illustration 10.25
// A program to show Tree structured data arrangement
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 Swing JColorChooser: The JColorChooser class is used to create a color chooser dialog
box so that user can select any color. It inherits JComponent class.
Illustration 10.26
// A program to show choose colour using JColorChooser
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ColorChooserExample extends JFrame implements ActionListener {
JButton b;Container c;
ColorChooserExample(){
c=getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("color");
b.addActionListener(this);
c.add(b); }
public void actionPerformed(ActionEvent e) {
Color initialcolor=Color.RED;
Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
c.setBackground(color);
}
public static void main(String[] args) {
ColorChooserExample ch=new ColorChooserExample();
ch.setSize(400,400);
ch.setVisible(true);
ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Java Swing 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.
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 Swing JSlider: The Java JSlider class is used to create the slider. By using JSlider, a user
can select a value from a specific range.
import javax.swing.*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel);
}
public static void main(String s[]) {
SliderExample1 frame=new SliderExample1();
frame.pack();
frame.setVisible(true);
}
}
Java Swing 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.
Illustration 10.29
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);
f.setLayout(null);
f.setVisible(true);
}
}
Java Swing JFileChooser: The object of JFileChooser class represents a dialog window from
which the user can select file. It inherits JComponent class.
Below is the declaration for javax.swing.JFileChooser
class. public�class�JFileChooser�extends�JComponent�implements�Accessible.�
�
Class JFileChooser : Constructors:
Illustration 10.30
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();
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(filep
ath));
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);}
}
Java Swing JToggelButton: JToggleButton is used to create toggle button, it is two-states
button to switch on or off.
Illustration 10.31
// A program to add a Toggle button
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class ToggleButtonExample extends JFrame implements ItemListener {
public static void main(String[] args) {
new ToggleButtonExample();
}
private JToggleButton button;
ToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}
Java Swing 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.
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
Java Swing 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.
Illustration 10.33
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);
}
}
Java Swing 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.
Illustration 10.34
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample() {
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new PanelExample();
}
}
Java Swing 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.
Class JFrame : Fields:��
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);
}
}
Methods used :
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class Calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
// store oprerator and operands
String s0, s1, s2;
// default constrcutor
Calculator()
{
s0 = s1 = s2 = "";
}
// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("Swing Calculator");
try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelCl
assName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
// create a object of class
Calculator c = new Calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, b
e, beq, beq1;
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
beq1 = new JButton("=");
// create operator buttons
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");
// create . button
be = new JButton(".");
// create a panel
JPanel p = new JPanel();
// add action listeners
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
// add elements to panel
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
// set Background of panel
p.setBackground(Color.blue);
// add panel to frame
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
// if the value is a number
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) ==
'.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDoubl
e(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDoubl
e(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDoubl
e(s2));
else
te = (Double.parseDouble(s0) * Double.pa
rseDouble(s2));
// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;
// make the operand blank
s2 = "";
}
// set the value of text
l.setText(s0 + s1 + s2);
}
}
}
Practice Questions
Practice 10.1
//Simple Application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
try {
UIManager.setLookAndFeel(lookAndFeel);
}
catch (UnsupportedLookAndFeelException e){
}
catch(ClassNotFoundException e){
}
catch (Exception e){
}
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Practice 9.2
//Dialog example
import javax.swing.JOptionPane;
//Input Dialog
ans = JOptionPane.showInputDialog(null, "Speed in miles per hour?");
double mph = Double.parseDouble(ans);
double kph = 1.621 * mph;
// Message Dialog
JOptionPane.showMessageDialog(null, "KPH = " + kph);
// Warning message
JOptionPane.showMessageDialog(null,"Please pay attention", "A warning
message",
JOptionPane.WARNING_MESSAGE);
// Question message
JOptionPane.showMessageDialog(null,"Are you sleeping", "An questi
on message",
JOptionPane.QUESTION_MESSAGE );
// Option Dialog
Object[] options = {"Yes", "No", "Don't know"};
int n = JOptionPane.showOptionDialog(
null,
"Feeling hungry?",
"A Silly Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
System.exit(0);
}
}
Practice 9.3
//example of Box layout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new PasswordFrame(frame));
frame.setSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT
));
frame.setLocation(250,200);
frame.setResizable(false);
frame.show();
}
/**
A frame that uses box layouts to organize various components.
*/
class PasswordFrame extends JPanel
{
public PasswordFrame(JFrame frame)
{
passFrame = frame;
// construct the left vertical box
JLabel label1 = new JLabel("Name");
label1.setForeground(Color.yellow);
//xxxxx.setComponentOrientation( ComponentOrien
tation.RIGHT_TO_LEFT);
button1.setBackground(Color.gray);
button1.setForeground(Color.yellow);
button1.setBorder(BorderFactory.createRaisedBevelBorder()
);
button1.setActionCommand(OK);
button1.addActionListener(new buttonListener());
button2.setBackground(Color.gray);
button2.setForeground(Color.yellow);
button2.setBorder(BorderFactory.createRaisedBevelBorder()
);
button2.setActionCommand(CANCEL);
button2.addActionListener(new buttonListener());
if (buttonPressed.equals(OK))
{
Container contentPane = messageDialog.getContentPane();
contentPane.add(new JLabel(" Success !! Wish you all the best"));
messageDialog.setSize(new Dimension(250,100));
messageDialog.setLocation(250+200, 200+100);
contentPane.setBackground(new Color(252, 215, 180));
messageDialog.show();
}
else
{
}
}
};
JFrame passFrame;
JDialog messageDialog = new JDialog(passFrame, "Login Message");
Practice 9.4
//Example of Button Demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
public ButtonDemo() {
ImageIcon leftButtonIcon = new ImageIcon("images/rightIco
n.gif");
ImageIcon middleButtonIcon = new ImageIcon("images/midIco
n.gif");
ImageIcon rightButtonIcon = new ImageIcon("images/leftIco
n.gif");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Practice 9.5
//Flow layout Demo
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.ComponentOrientation;
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
Practice 9.6
//Example with font
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
A frame that uses a grid bag layout to arrange font
selection components.
*/
class FontDialogFrame extends JFrame
{
public FontDialogFrame()
{
setTitle("FontDialog");
setSize(WIDTH, HEIGHT);
// construct components
face.addActionListener(listener);
size.addActionListener(listener);
bold = new JCheckBox("Bold");
bold.addActionListener(listener);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
constraints.weightx = 0;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
add(bold, constraints, 0, 2, 2, 1);
add(italic, constraints, 0, 3, 2, 1);
constraints.fill = GridBagConstraints.BOTH;
add(sample, constraints, 2, 0, 1, 4);
}
/**
A convenience method to add a component to given grid bag
layout locations.
@param c the component to add
@param constraints the grid bag constraints to use
@param x the x grid position
@param y the y grid position
@param w the grid width
@param h the grid height
*/
public void add(Component c, GridBagConstraints constraints,int x, int
y, int w, int h)
{
constraints.gridx = x;
constraints.gridy = y;
constraints.gridwidth = w;
constraints.gridheight = h;
getContentPane().add(c, constraints);
}
/**
An action listener that changes the font of the
sample text.
*/
private class FontAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String fontFace = (String)face.getSelectedItem();
int fontStyle = (bold.isSelected() ? Font.BOLD : 0)
+ (italic.isSelected() ? Font.ITALIC : 0);
int fontSize = Integer.parseInt(
(String)size.getSelectedItem());
Font font = new Font(fontFace, fontStyle, fontSize);
sample.setFont(font);
sample.repaint();
}
}
}
Practice 9.7
//Voting example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
this.frame = frame;
JLabel title;
System.out.println("passed createSimpleDialogBox");
radioButtons[3].setActionCommand(yncCommand);
voteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String command = group.getSelection().ge
tActionCommand();
//ok dialog
if (command == defaultMessageCommand) {
JOptionPane.showMessageDialog(fr
ame,
"This candidate is a dog. Inv
alid vote.");
//yes/no dialog
} else if (command == yesNoCommand) {
int n = JOptionPane.showConfirmD
ialog(frame,
�This candidate is a convicted felon
. \nDo you still want
to vote for her?",
"A Follow-up Question",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION)
{
setLabel("OK. Keep an e
ye on your wallet.");
} else if (n == JOptionPane.NO_O
PTION) {
setLabel("Whew! Good ch
oice.");
} else {
setLabel("It is your ci
vic duty to cast your vote.");
}
"Well, if I must"};
int n = JOptionPane.showOptionDi
alog(frame,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if (n == JOptionPane.YES_OPTION)
{
setLabel("Excellent cho
ice.");
} else if (n == JOptionPane.NO_O
PTION) {
setLabel("Whatever you
say. It's your vote.");
} else if (n == JOptionPane.CANC
EL_OPTION) {
setLabel("Well, I'm cer
tainly not going to make you vote.");
} else {
setLabel("It is your ci
vic duty to cast your vote.");
}
}
return;
}
});
System.out.println("calling createPane");
return createPane(simpleDialogDesc + ":",
radioButtons,
voteButton);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
Practice 9.8
//combo box with different window
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JPanel cards;
final static String BUTTONPANEL = "JPanel with JButtons";
final static String TEXTPANEL = "JPanel with JTextField";
public CardWindow() {
Container contentPane = getContentPane();
cards.add(p1, BUTTONPANEL);
cards.add(p2, TEXTPANEL);
contentPane.add(cards, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (inAnApplet) {
dispose();
} else {
System.exit(0);
}
}
});
}
window.setTitle("CardLayout");
window.pack();
window.setVisible(true);
}
}
Practice 9.9
//tab window example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public TabWindow() {
Container contentPane = getContentPane();
contentPane.add(tabbedPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (inAnApplet) {
dispose();
} else {
System.exit(0);
}
}
});
}
window.setTitle("TabWindow");
window.pack();
window.setVisible(true);
}
}
Practice 9.10
//Create an applet for digital clock
DigitalClockApplet.java
import java.awt.Container;
import java.awt.Dimension;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
jDay.setText("Show Day");
this.add(jDay);
jDay.setBounds(30, 100, 150, 22);
jDate.setText("Show Date");
this.add(jDate);
jDate.setBounds(190, 100, 180, 22);
jSec.setText("Show Seconds");
this.add(jSec);
jSec.setBounds(380, 100, 160, 22);
this.jDate.setSelected(true);
this.jDay.setSelected(true);
this.jSec.setSelected(true);
}
}
DigitalClockApplet.htm
< HTML>
< HEAD>
< / HEAD>
< BODY BGCOLOR="000000">
< CENTER>
< applet code="DigitalClockApplet.class" WIDTH=660 HEIGHT=150>
< / applet>
< / CENTER>
< / BODY>
< / HTML>
Practice 9.11
// Create an Application for Digital Clock
import java.awt.Container;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
Practice 9.12
//Create an applet for calculator
CalcApplet.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalcApplet extends JApplet
{
public void init()
{
Container contentPane=getContentPane();
CalculatorPanel panel=new CalculatorPanel();
contentPane.add(panel);
}
}
result = 0;
lastCommand = "=";
start = true;
addButton("sin",command);
addButton("cos",command);
addButton("tan",command);
addButton("A/C",command);
addButton("asin",command);
addButton("acos",command);
addButton("atan",command);
addButton("n!",command);
addButton("log",command);
addButton("ln",command);
addButton("Pi",insert);
addButton("e",insert);
addButton("x^(1/y)",command);
addButton("x^y",command);
addButton("Sqrt",command);
addButton("/",command);
addButton("9",insert);
addButton("8",insert);
addButton("7",insert);
addButton("x",command);
addButton("6",insert);
addButton("5",insert);
addButton("4",insert);
addButton("+",command);
addButton("3",insert);
addButton("2",insert);
addButton("1",insert);
addButton("_",command);
addButton("0",insert);
addButton("+/-",command);
addButton("=",command);
addButton(".",insert);
add(panel,BorderLayout.CENTER);
}
display.setText(""+result);
}
private int fact(int n)
{
if((n==0)||(n==1)) return 1;
else return n*fact(n-1);
}
CalcApplet.htm
< HTML>
< HEAD>
< / HEAD>
< BODY BGCOLOR="000000">
< CENTER>
< applet code="CalcApplet.class"WIDTH=400 HEIGHT=400>
< / applet>
< / CENTER>
< / BODY>
< / HTML>
Practice 9.13
//Create an application for calculator
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
Assignment
Develop a swing application for login validation of a system as shown in the figure. The
application shows two options: one �Sign up� and another �Sign in�. When �Sign up� is
selected, a new screen will appear for asking name, username, password. If the entered
username and password do not exist in the database, it will show a successful message
�[Name] has successfully registered� and store corresponding username, password in the
database, otherwise the message �[Name] already exists in the system� will be displayed. On
the other hand, when �Sign In� option is selected, the user will be prompted to enter
username, password as shown in the figure. Eventually, the application checks whether
username and password both match with some entry in the database. If such entry found in the
database, then a welcome message �Welcome [Name]� will appear, otherwise an
unsuccessful login message �Wrong username/password� will be displayed. For message
display, the swing dialogs can be used. You should have some login information in your
database so that all four situations can be validated.
Q&A
Q: What is difference between invokeAndWait and invokeLater in Java?
A: Swing is not thread-safe and at same time you can not perform time
consuming task in EDT thread. InvokeAndWait and InvokeLater method allows
to enqueue task for EDT thread to perform, InvokeAndWait is a blocking
method in Java and does it synchronously and invokeLater does it
asynchronously. Since GUI can only be updated in Event dispatcher thread, if
you need to show progress of any task, you can use these two methods.
Q: What is EDT thread in Swing?
A: EDT stands for Event dispatcher thread. EDT is one of the most important
thing to learn about Swing, Since Swing is single-threaded all GUI drawing and
event handling is done in EDT thread and that's why its recommended not to
perform any time consuming task e.g. connecting to database or opening
network connection in Event Dispatcher thread or EDT thread. If you do that, it
may lead to frozen or hung GUI. This question leads to several other questions
in Java, e.g. If you can not open database connection in EDT thread than how
will you open db connection with button click etc. well this can be done by
spawning a new thread from button click and opening db connection there.
Q: How to change a button from enable to disable after click ?
A: When button is clicked an action event is fired which can be captured by
implementing ActionListener interface and actionPerformed(ActionEvent ae)
method. You can then call button.setEnable(false) to disable this button.
Q: Why Swing is called light weight ?
A: Most of Swing component are inherited form JComponent and doesn't required
a native peer and that's why they are referred as light weight component. light
weight component implement look and feel in Java rather than using look and
feel of native component and that's why Swing's look and feel remains same
across platform.
Q: Is Swing Thread safe in Java ?
A: No, Swing is not thread-safe in Java. Swing components are not thread-safe
they can not be modified from multiple threads. All swing components are
designed to be updated by using Event dispatcher thread or EDT thread
Q: Which method of Swing are thread-safe?
A: Only couple of methods like repaint() and revalidate() are thread-safe in Swing,
i.e. they can be called from multiple threads without additional synchronization
in Java.
Q: What is difference between Container and Component ?
A: Main difference between Container and Component is that former can hold
other components e.g. JFrame which is used as container to hold other
components e.g. JButton.
Q: What is the purpose of action interface in Swing?
A: Action is performed on a state to allow it to change. It defines the interface that
it is implementing. The library that is used for the action interface is
javax.swing.Action. This action interface extends the ActionListener interface
class that is being provided from the AWT. Action interface allow the concrete
classes to implement the actionPerformed() method and provide the action that
is associated with it. The use of actionPerformed() method allow the
implementation of the behavior that is desired in the programming and allow it
to show the functionality of the action class. The action can be added to the
container class that accepts the parameters on an event like JMenu,
JPopupMenu, or JtoolBar. The container used in this automatically registers
the action that is taken on the event and it acts as an ActionListener of the user
interface.
Q: Explain Thread Rule in Swing?
A: Once a swing component has been realized, i.e. the component has been
painted on screen or it is ready to painted, all the code that might affect or
depend on the state of that component should be executed in the event
dispatching thread. This is called thread rule in swing..
Q: What is the use of double buffering in Swing?
A: Double-buffering is the process of drawing graphics into an off-screen image
buffer and then copying the contents of the buffer to the screen all at once. For
complex graphics, using double-buffering can reduce flickering.
Q: What is the purpose of Serialization in Swing?
A: Serialization is used when an object extends the Jcomponent class. The
object's data in this case points out to the stream that is written or serialized
and gives an output stream. This output stream can be sent through then
network and it can be saved in the file if required. The serialized file can be de-
serialized in the memory. This will allow the operation to continue to perform
the original state functions that were getting used. The serialization used in
object allows easy retrieval of the object data and easy transmission of state
data from one place to another. This can also be placed in custom made
storage files that provide the transfer of the components to be fast and it uses
the concept of virtual machine that transfers from one machine to another
machine. It uses the remote method invocation to allow the use of distributed
computing that provide with some exceptions to the use of transient keyword.
The components can be serialized using the classes that can pass the
reference to an object using the writeObject() method of the
ObjectOutputStream object this way it calls the serialization function
recursively.
Q: How do you classify Swing Components?
A: Swing components are classified under the following headings:
1.Top level containers � The containers at the top of any swing component h
ierarchy are:
Applet
Dialog
Frame
2.General purpose containers � The intermediate containers are
Panel
Scroll pane
Split pane
Tabbed pane
Tool bar
A FRAME can exists on its own , where as a DIALOG cannot exist on its own.
In other words, FRAME is a primary window, where as the DIALOG box is
secondary window. The dialog boxes are of two types:
• modal � This dialog won't let the user interact with the remaining
containers/windows until he deals with it.
• modeless - The user can interact with other windows as well as the dialog
box, e.g. the toolbox.
There is no default constructor for a DIALOG. The following statement
constructs a dialog box: