Chapter 10

Java Swing

by Debasis Samanta


CONTENTS

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.

AWT versus Swing


Figure 10.1 :AWT versus Swing

NoteThe Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Swing in depth

Hierarchy of Java Swing classes:


Figure 10.2 :Hierarchy of Java Swing classes

Commonly used methods in Component class:


Figure 10.3 :Commonly used methods in Component class:

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.

    JFrame object :

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


    Figure 10.4 :JFrame object

    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
      
    //Create a Swing button
    
    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();  
    	}
    }
    

    Java Swing 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. Below is the declaration for javax.swing.JButton class.
    public class JButton extends AbstractButton implements Accessible 

    Class JButton : Constructors:

    Class JButton : Methods:

    Creating a JButton : An 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. also illustarte Java JButton : An example with ActionListener


    Illustration 10.6
    
    // Button with Action Listner
    import java.awt.event.*;  
    import javax.swing.*;    
    public class ButtonExample {  
    public static void main(String[] args) {  
        JFrame f=new JFrame("Button Example");  
        final JTextField tf=new JTextField();  
        tf.setBounds(50,50, 150,20);  
        JButton b=new JButton("Click Here");  
        b.setBounds(50,100,95,30);  
        b.addActionListener(new ActionListener(){  
        public void actionPerformed(ActionEvent e){  
                tf.setText("Welcome to Javatpoint.");  
            }  
        });  
        f.add(b);f.add(tf);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);   
    }  
    }   
    

    Java JButton : Displaying image on the button


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

    Java Swing 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.

    Below is the declaration for javax.swing.JLabel class. public class JLabel extends JComponent implements SwingConstants, Accessible 


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

    Java JLabel : An example with ActionListener


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

    Java Swing JTextField:

    The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class.

    Below is the declaration for javax.swing.JTextField class. public class JTextField extends JTextComponent implements SwingConstants

    Class JTextField : Constructors

    Class JTextField : Methods


    Illustration 10.10
    /*
    Simple calculator for Addition and Subtraction of numbers in TextField
    */
    
    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 Swing 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.

    Class JTextArea : constructors:

    Class JTextArea : methods:


    Illustration 10.11
    /*
    Simple program to find number of words and characters in a TextArea
    */
    
    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 JTextArea : An example with ActionListener:

    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.

    The declaration for javax.swing.JPasswordField class is public class JPasswordField extends JTextField.

    Class JPasswordField : Constructors:

    Illustration 10.12
    /*
    Simple program to make a login GUI using TextField, PasswordField and Login Button
    */
    
    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:

    Class JCheckBox : Methods:

    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.

    Below is the declaration for javax.swing.JRadioButton class. public class JRadioButton extends JToggleButton implements Accessible  

    Class JRadioButton : Constructors:

    Class JRadioButton : Methods:

    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:

    Class JComboBox : Methods:

    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.

    Below is the declaration for javax.swing.JList class. public class  JList extends JComponent implements Scrollable, Accessible    

    Class JList : Constructors:

    Class JList : Methods:

    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.

    Below is the declaration for javax.swing.JOptainPane class. public class JOptionPane extends JComponent implements Accessible   

    Class JOptionPane : Constructors:

    Class JOptionPane : Methods:

    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.

    Below is the declaration for javax.swing.JScrollBar class. public class JScrollBar extends JComponent implements Adjustable, Accessible   

    Class JScrollBar: Constructors:

    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.

    Below is the declaration for javax.swing.JMenuBar class. public class JMenuBar extends JComponent implements MenuElement, Accessible  

    Java Swing JMenu: The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class.

    Below is the declaration for javax.swing.JMenuItem class JMenu extends JMenuItem implements MenuElement, Accessible

    Class JMenuItem: 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.

    Below is the declaration for javax.swing.JMenuItem class. public class JMenuItem extends AbstractButton implements Accessible, MenuElement  

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

    Java Swing JPopupMenu: JPopupMenu can be dynamically popped up at specific position within a component. It inherits the JComponent class.

    Below is the declaration for javax.swing.JPopupMenu class. public class JPopupMenu extends JComponent implements Accessible, MenuElement  

    Class JPopupMenu : Constructors:

    Illustration 10.21
    // A program to show some menu using PopupMenu
    
    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.

    Class JCheckBoxMenuItem: Constructors:

    Class JCheckBoxMenuItem : Methods:

    Illustration 10.22
    // A program to show check box menu item in menu
    
    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.

    Below is the declaration for javax.swing.JSeparator class public class  JSeparator extends JComponent implements SwingConstants, Accessible   

    Class JSeparator : Constructors:

    Class JSeparator : Methods:

    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.

    Below is the declaration for javax.swing.JProgressBar class. public class JProgressBar extends JComponent implements SwingConstants, Accessible  

    Class JProgressBar : Constructors:

    Class JProgressBar : Methods:

    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, Accessible 

    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.

    Below is the declaration for javax.swing.JColorChooser class. public class JColorChooser extends JToggleButton implements Accessible   

    Class JColorChooser: Constructors:

    Class JColorChooser : Methods:

    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.

    Below is the declaration for javax.swing.JTabbedPane class. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants.  

    Class JTabbedPane : Constructors:

    Illustration 10.27
    // A program to show multiple tabs using JTabbedPane
    
    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.

    Class JSlider : Constructors:

    Class JSlider : Methods:

    Illustration 10.28
    // A program to implement slider input using JSlider
    
    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.

    Below is the declaration for javax.swing.JSpinner class. public class  JSpinner extends JComponent implements Accessible. 

    Class JSpinner : Constructors:

    Class JSpinner : Methods:

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

    Java Swing JToggelButton: JToggleButton is used to create toggle button, it is two-states button to switch on or off.

    Class JToggleButton : Constructors:

    Class JToggleButton : Methods:

    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.

    Class JToolBar : Constructors:

    Class JToolBar : Methods:

    Illustration 10.32
    
    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;  
      
    public class ToolBarExample {  
        public static void main(final String args[]) {  
            JFrame myframe = new JFrame("JToolBar Example");  
            myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
            JToolBar toolbar = new JToolBar();  
            toolbar.setRollover(true);   
            JButton button = new JButton("File");  
            toolbar.add(button);  
            toolbar.addSeparator();  
            toolbar.add(new JButton("Edit"));  
            toolbar.add(new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-3", "Opt-4" }));  
            Container contentPane = myframe.getContentPane();  
            contentPane.add(toolbar, BorderLayout.NORTH);  
            JTextArea textArea = new JTextArea();  
            JScrollPane mypane = new JScrollPane(textArea);  
            contentPane.add(mypane, BorderLayout.EAST);  
            myframe.setSize(450, 250);  
            myframe.setVisible(true);  
        }  
    }   
    

    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.

    Class JViewport : Fields:

    Class JViewport : Constructors:

    Class JViewport :Methods:

    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);  
      
            JLabel label = new JLabel("Label");  
            label.setPreferredSize(new Dimension(1000, 1000));   
            JScrollPane jScrollPane = new JScrollPane(label);  
      
            JButton jButton1 = new JButton();  
            jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
            jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
            jScrollPane.setViewportBorder(new LineBorder(Color.RED));  
            jScrollPane.getViewport().add(jButton1, null);  
      
            frame.add(jScrollPane, BorderLayout.CENTER);  
            frame.setSize(400, 150);  
            frame.setVisible(true);  
        }  
    } 
    

    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.

    Below is the declaration for javax.swing.JPanel class. public class  JPanel extends JComponent implements Accessible     

    Class JPanel : Constructors:

    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:  

    Class JFrame : Constructors:

    Class JFrame : Methods:

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

    Java Swing Calculator:

    Methods used :
    
    add(Component c) : adds component to container.
    
    addActionListenerListener(ActionListener d) : add actionListener for specified component
    
    setBackground(Color c) : sets the background color of the specified container
    
    setSize(int a, int b) : sets the size of container to specified dimensions.
    
    setText(String s) : sets the text of the label to s.
    
    getText() : returns the text of the label
    

    Illustration 10.36
    // Java program to create a simple calculator
    // with basic +, -, /, * using java swing elements
    
    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.getSystemLookAndFeelClassName());
    		}
    		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, be, 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.parseDouble(s2));
    			else if (s1.equals("-"))
    				te = (Double.parseDouble(s0) - Double.parseDouble(s2));
    			else if (s1.equals("/"))
    				te = (Double.parseDouble(s0) / Double.parseDouble(s2));
    				else
    					te = (Double.parseDouble(s0) * Double.parseDouble(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.*;
    
    	public class SimpleApplication implements ActionListener {
    		private static String labelPrefix = "Number of button clicks: ";
    		private int numClicks = 0;
    		private final JLabel label = new JLabel(labelPrefix + "0    ");
    
    		public Component createComponents() {
    			JButton button = new JButton("I'm a Swing button!");
    			button.addActionListener(this);
    	  
    			/* An easy way to put space between a top-level container
    			 * and its contents is to put the contents in a JPanel
    			 * that has an "empty" border. */
    			JPanel pane = new JPanel(new GridLayout(0, 1));
    			pane.add(button);
    			pane.add(label);
    			pane.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));    
    			//top,left,bottom,right
    			return pane;
    		}
    
    		public void actionPerformed(ActionEvent e) {
    			numClicks++;
    			label.setText(labelPrefix + numClicks);
    		}
    		
    		private static void initLookAndFeel() {
    	   // METAL
    		 String lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel";
    	   // MOTIF
    		// String lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
    	   // WINDOWS
    		 // String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
    
    			try {
    					UIManager.setLookAndFeel(lookAndFeel);
    			} 
    			catch (UnsupportedLookAndFeelException e){
    			}
    			catch(ClassNotFoundException e){
    			}
    			catch (Exception e){
    			}
    		}
    
    		
    		private static void createAndShowGUI() {
    			
    			//Set the look and feel.
    			initLookAndFeel();
    			
    			//Make sure we have nice window decorations.
    			JFrame.setDefaultLookAndFeelDecorated(true);
    
    			//Create and set up the window.
    			JFrame frame = new JFrame("SimpleApplication");
    			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    			// Create a new instance of the application class
    			SimpleApplication app = new SimpleApplication();
    			Component contents = app.createComponents();
    			frame.getContentPane().add(contents, BorderLayout.CENTER);
    
    			//Display the window.
    			frame.pack();
    			frame.setVisible(true);
    		}
    		
    		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() {
    					createAndShowGUI();
    				}
    			});
    		}
    	}
    
    
    Practice 9.2
    	//Dialog example
    
    	import javax.swing.JOptionPane;
    
    	public class JOptionPaneExample {
    		public static void main(String[] args) {
    		String ans;
    		 
    	   //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 question message", 
    		 JOptionPane.QUESTION_MESSAGE );
    			
    		// Error message dialog
    		JOptionPane.showMessageDialog(null, "Error!", "An error message",  
    		  JOptionPane.ERROR_MESSAGE);
    			 
    		// Input dialog with choice 
    		   Object[] possibleValues = { "Enjoying", "Boring", "Sleep" };
    		   Object selectedValue = JOptionPane.showInputDialog(
    					  null,
    					"Choose one",
    					"Input",
    					JOptionPane.INFORMATION_MESSAGE,
    					null,
    					possibleValues,
    					possibleValues[0]);
    			 
    	 JOptionPane.showMessageDialog(null, "Hey, you are now feeling = " + selectedValue);		
    			 
    	// 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.*;
    
    	public class Password
    	{
    		public static void main(String[] args)
    		{  
    			JFrame frame = new JFrame("Password test");
    
    			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();
    		}
    
    		public static final int DEFAULT_WIDTH = 225;
    		public static final int DEFAULT_HEIGHT = 125;  
    	}
    
    	/**
    		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);
    		
    			JLabel label2 = new JLabel("Password");
    			label2.setForeground(Color.yellow);
    			label2.setDisplayedMnemonic('s');
    			label2.setDisplayedMnemonicIndex(3);
    			
    			Box hbox1 = Box.createVerticalBox();
    			hbox1.add(label1);
    			// separate labels with a 10-pixel strut
    			hbox1.add(Box.createVerticalStrut(10));
    			hbox1.add(label2);
    
    			// construct the right vertical box
    			JTextField textField1 = new JTextField(10);
    			textField1.setMaximumSize(textField1.getPreferredSize());
    
    			// declare password field
    			JPasswordField passwordField = new JPasswordField(10);
    			passwordField.setMaximumSize(passwordField.getPreferredSize());
    			passwordField.setEchoChar('@');
    				// passwordField.setActionCommand(OK);
    				// passwordField.addActionListener(this);
    			label2.setLabelFor(passwordField);
    
    				 //xxxxx.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT);
    
    			Box hbox2 = Box.createVerticalBox();
    			hbox2.add(textField1);
    			// separate textfields with a 10-pixel strut
    			hbox2.add(Box.createVerticalStrut(10));
    			hbox2.add(passwordField);
    
    			// construct the top horizontal box 
    			// by joining the left and roght horizontal boxes
    			Box hbox2a = Box.createHorizontalBox();
    			hbox2a.add(Box.createHorizontalStrut(10));
    			hbox2a.add(hbox1);
    			hbox2a.add(Box.createHorizontalStrut(10));
    			hbox2a.add(hbox2);
    			hbox2a.add(Box.createHorizontalStrut(10));
    
    			// construct the bottom horizontal box
    			JButton button1 = new JButton("   Ok   ");
    			JButton button2 = new JButton("Cancel");
    			
    			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());
    			
    			Box hbox3 = Box.createHorizontalBox();
    			hbox3.add(button1);
    				// use "glue" to push the two buttons apart
    				// hbox3.add(Box.createGlue());
    			hbox3.add(Box.createHorizontalStrut(30));
    			hbox3.add(button2);
    
    			// add the two horizontal boxes inside a vertical box
    			Box vbox = Box.createVerticalBox();
    			vbox.add(hbox2a);
    			vbox.add(Box.createVerticalStrut(20));
    			vbox.add(hbox3);
    
    				 // Container contentPane = getContentPane();
    				 // contentPane.setBackground(Color.blue);
    				 // contentPane.add(vbox, BorderLayout.CENTER);
    				 //
    			 add(vbox, BorderLayout.CENTER);
    			 setBackground(Color.blue);
    			
    			}
    
    		class buttonListener implements ActionListener
    		{
    			public void actionPerformed(ActionEvent e)
    			{
    			   String buttonPressed = e.getActionCommand();
    
    				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"); 
    
    		private static String OK = "ok";
    		private static String CANCEL = "cancel"; 
    	}
    
    
    
    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 class ButtonDemo extends JPanel implements ActionListener {
    		protected JButton b1, b2, b3;
    
    		public ButtonDemo() {
    			ImageIcon leftButtonIcon = new ImageIcon("images/rightIcon.gif");
    			ImageIcon middleButtonIcon = new ImageIcon("images/midIcon.gif");
    			ImageIcon rightButtonIcon = new ImageIcon("images/leftIcon.gif");
    
    			b1 = new JButton("Disable middle button", leftButtonIcon);
    			b1.setVerticalTextPosition(AbstractButton.CENTER);
    			b1.setHorizontalTextPosition(AbstractButton.LEFT);
    			b1.setMnemonic(KeyEvent.VK_D);
    			b1.setActionCommand("disable");
    
    			b2 = new JButton("Middle button", middleButtonIcon);
    			b2.setVerticalTextPosition(AbstractButton.BOTTOM);
    			b2.setHorizontalTextPosition(AbstractButton.CENTER);
    			b2.setMnemonic(KeyEvent.VK_M);
    
    			b3 = new JButton("Enable middle button", rightButtonIcon);
    			//Use the default text position of CENTER, RIGHT.
    			b3.setMnemonic(KeyEvent.VK_E);
    			b3.setActionCommand("enable");
    			b3.setEnabled(false);
    
    			//Listen for actions on buttons 1 and 3.
    			b1.addActionListener(this);
    			b3.addActionListener(this);
    
    			b1.setToolTipText("Click this button to disable the middle button.");
    			b2.setToolTipText("This middle button does nothing when you click it.");
    			b3.setToolTipText("Click this button to enable the middle button.");
    
    			//Add Components to this container, using the default FlowLayout. 
    			add(b1);
    			add(b2);
    			add(b3);
    		}
    
    		public void actionPerformed(ActionEvent e) {
    			if (e.getActionCommand().equals("disable")) {
    				b2.setEnabled(false);
    				b1.setEnabled(false);
    				b3.setEnabled(true);
    			} else { 
    				b2.setEnabled(true);
    				b1.setEnabled(true);
    				b3.setEnabled(false);
    			}
    		}
    		
    		public static void main(String[] args) {
    			JFrame frame = new JFrame("ButtonDemo");
    
    			frame.addWindowListener(new WindowAdapter() {
    				public void windowClosing(WindowEvent e) {
    					System.exit(0);
    				}
    			});
    
    			frame.getContentPane().add(new ButtonDemo(), BorderLayout.CENTER);
    			frame.pack();
    			frame.setVisible(true);
    		}
    	}
    
    
    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;
    
    	public class FlowLayoutDemo {
    		public static boolean RIGHT_TO_LEFT = true;
    
    		public static void addComponents(Container contentPane) {
    			if (RIGHT_TO_LEFT) {
    				contentPane.setComponentOrientation(
    					ComponentOrientation.RIGHT_TO_LEFT);
    			}
    			contentPane.setLayout(new FlowLayout());
    
    			contentPane.add(new JButton("Button 1"));
    			contentPane.add(new JButton("Button 2"));
    			contentPane.add(new JButton("Button 3"));
    			contentPane.add(new JButton("Long-Named Button 4"));
    			contentPane.add(new JButton("5"));
    		}
    
    		/**
    		 * 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);
    
    			//Create and set up the window.
    			//JFrames decorated by the Java look and feel
    			//can't get smaller than their minimum size.
    			//We specify a skinnier minimum size than the
    			//content pane will cause the frame to request,
    			//so that you can see what happens when you
    			//drag the window so that it's narrower than a
    			//single row.
    			JFrame frame = new JFrame("FlowLayoutDemo") {
    				public Dimension getMinimumSize() {
    					Dimension prefSize = getPreferredSize();
    					return new Dimension(100, prefSize.height);
    				}
    			};
    			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    			//Set up the content pane.
    			addComponents(frame.getContentPane());
    			//Display the window.
    			frame.pack();
    			frame.setVisible(true);
    		}
    
    		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() {
    					createAndShowGUI();
    				}
    			});
    		}
    	}
    
    
    
    Practice 9.6
    	//Example with font 
    	import java.awt.*;
    	import java.awt.event.*;
    	import javax.swing.*;
    	import javax.swing.event.*;
    
    	public class FontDialog
    	{
    	   public static void main(String[] args)
    	   {  
    		  FontDialogFrame frame = new FontDialogFrame();
    		  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		  frame.show();
    	   }
    	}
    
    	/**
    	   A frame that uses a grid bag layout to arrange font
    	   selection components.
    	*/
    	class FontDialogFrame extends JFrame
    	{  
    	   public FontDialogFrame()
    	   {  
    		  setTitle("FontDialog");
    		  setSize(WIDTH, HEIGHT);
    
    		  Container contentPane = getContentPane();
    		  GridBagLayout layout = new GridBagLayout();
    		  contentPane.setLayout(layout);
    
    		  ActionListener listener = new FontAction();
    
    		  // construct components
    		  
    		  JLabel faceLabel = new JLabel("Face: ");
    
    		  face = new JComboBox(new String[] 
    			 {  
    				"Serif", "SansSerif", "Monospaced", 
    				"Dialog", "DialogInput" 
    			 });
    		  
    		  face.addActionListener(listener);
    
    		  JLabel sizeLabel = new JLabel("Size: ");
    
    		  size = new JComboBox(new String[]
    			 {
    				"8", "10", "12", "15", "18", "24", "36", "48"
    			 });
    
    		  size.addActionListener(listener);
    
    		  bold = new JCheckBox("Bold");
    		  bold.addActionListener(listener);
    
    		  italic = new JCheckBox("Italic");
    		  italic.addActionListener(listener);
    
    		  sample = new JTextArea();
    		  sample.setText(
    			 "The quick brown fox jumps over the lazy dog");
    		  sample.setEditable(false);
    		  sample.setLineWrap(true);
    		  sample.setBorder(BorderFactory.createEtchedBorder());
    
    		  // add components to grid
    
    		  GridBagConstraints constraints = new GridBagConstraints();
    
    		  constraints.fill = GridBagConstraints.NONE;
    		  constraints.anchor = GridBagConstraints.EAST;
    		  constraints.weightx = 0;
    		  constraints.weighty = 0;
    
    		  add(faceLabel, constraints, 0, 0, 1, 1);
    		  add(sizeLabel, constraints, 0, 1, 1, 1);
    
    		  constraints.fill = GridBagConstraints.HORIZONTAL;
    		  constraints.weightx = 100;
    		  
    		  add(face, constraints, 1, 0, 1, 1);
    		  add(size, constraints, 1, 1, 1, 1);
    
    		  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);
    	   }
    
    	   public static final int WIDTH = 300;
    	   public static final int HEIGHT = 200;  
    
    	   private JComboBox face;
    	   private JComboBox size;
    	   private JCheckBox bold;
    	   private JCheckBox italic;
    	   private JTextArea sample;
    
    	   /**
    		  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.*;
    
    	public class VoteDialog extends JPanel {
    		JLabel label;
    		JFrame frame;
    		String simpleDialogDesc = "The candidates";
    
    		public VoteDialog(JFrame frame) {
    			super(new BorderLayout());
    
    			this.frame = frame;
    			JLabel title;
    			
    			//Create the components.
    			JPanel choicePanel = createSimpleDialogBox();
    			
    			System.out.println("passed createSimpleDialogBox");
    					
    			title = new JLabel("Click the \"Vote\" button"
    							   + " once you have selected a candidate.",
    							   JLabel.CENTER);
    			
    			label = new JLabel("Vote now!", JLabel.CENTER);
    			label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
    			choicePanel.setBorder(BorderFactory.createEmptyBorder(20,20,5,20));
    
    			//Lay out the main panel.
    			add(title, BorderLayout.NORTH);  
    			add(label, BorderLayout.SOUTH);        
    			add(choicePanel, BorderLayout.CENTER);
    		}
    
    		void setLabel(String newText) {
    			label.setText(newText);
    		}
    
    		private JPanel createSimpleDialogBox() {
    			final int numButtons = 4;
    			JRadioButton[] radioButtons = new JRadioButton[numButtons];
    			
    			final ButtonGroup group = new ButtonGroup();
    
    			JButton voteButton = null;
    
    			final String defaultMessageCommand = "default";
    			final String yesNoCommand = "yesno";
    			final String yeahNahCommand = "yeahnah";
    			final String yncCommand = "ync";
    
    			radioButtons[0] = new JRadioButton(
    			  "Candidate 1: Sparky the Dog");
    			radioButtons[0].setActionCommand(defaultMessageCommand);
    
    			radioButtons[1] = new JRadioButton(
    			   "Candidate 2: Shady Sadie");
    			radioButtons[1].setActionCommand(yesNoCommand);
    
    			radioButtons[2] = new JRadioButton(
    				"Candidate 3: R.I.P. McDaniels");
    			radioButtons[2].setActionCommand(yeahNahCommand);
    
    			radioButtons[3] = new JRadioButton(
    				"Candidate 4: Duke the JavaTM Platform Mascot");
    			radioButtons[3].setActionCommand(yncCommand);
    
    
    			for (int i = 0; i < numButtons; i++) {
    				group.add(radioButtons[i]);
    			}
    
    			//Select the first button by default.
    			radioButtons[0].setSelected(true);
    
    			voteButton = new JButton("Vote");
    			
    			voteButton.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent e) {
    					String command = group.getSelection().getActionCommand();
    
    					//ok dialog
    					if (command == defaultMessageCommand) {
    						JOptionPane.showMessageDialog(frame,
    						   "This candidate is a dog. Invalid vote.");
    
    					//yes/no dialog
    					} else if (command == yesNoCommand) {
    						int n = JOptionPane.showConfirmDialog(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 eye on your wallet.");
    						} else if (n == JOptionPane.NO_OPTION) {
    							setLabel("Whew! Good choice.");
    						} else {
    							setLabel("It is your civic duty to cast your vote.");
    						}
    
    					//yes/no (with customized wording)
    					} else if (command == yeahNahCommand) {
    						Object[] options = {"Yes, please", "No, thanks"};
    						int n = JOptionPane.showOptionDialog(frame,
    					   "This candidate is deceased. \nDo you still want to vote for him?",
    						   "A Follow-up Question",
    						   JOptionPane.YES_NO_OPTION,
    						   JOptionPane.QUESTION_MESSAGE,
    						   null,
    						   options,
    						   options[0]);
    						if (n == JOptionPane.YES_OPTION) {
    							setLabel("I hope you don't expect much from your candidate.");
    						} else if (n == JOptionPane.NO_OPTION) {
    							setLabel("Whew! Good choice.");
    						} else {
    							setLabel("It is your civic duty to cast your vote.");
    						}
    
    					//yes/no/cancel (with customized wording)
    					} else if (command == yncCommand) {
    						Object[] options = {"Yes!",
    											"No, I'll pass",
    											"Well, if I must"};
    						int n = JOptionPane.showOptionDialog(frame,
    										"Duke is a cartoon mascot. \nDo you  "
    										+ "still want to cast your vote?",
    										"A Follow-up Question",
    										JOptionPane.YES_NO_CANCEL_OPTION,
    										JOptionPane.QUESTION_MESSAGE,
    										null,
    										options,
    										options[2]);
    						if (n == JOptionPane.YES_OPTION) {
    							setLabel("Excellent choice.");
    						} else if (n == JOptionPane.NO_OPTION) {
    							setLabel("Whatever you say. It's your vote.");
    						} else if (n == JOptionPane.CANCEL_OPTION) {
    							setLabel("Well, I'm certainly not going to make you vote.");
    						} else {
    							setLabel("It is your civic duty to cast your vote.");
    						}
    					}
    					return;
    				}
    			});
    			System.out.println("calling createPane");
    			return createPane(simpleDialogDesc + ":",
    							  radioButtons, 
    							  voteButton);                    
    		}
    		
    		private JPanel createPane(String description,
    								  JRadioButton[] radioButtons,
    								  JButton showButton) {
    			int numChoices = radioButtons.length;
    			JPanel box = new JPanel();
    			JLabel label = new JLabel(description);
    
    			box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    			box.add(label);
    
    			for (int i = 0; i < numChoices; i++) {
    				box.add(radioButtons[i]);
    			}
    
    			JPanel pane = new JPanel(new BorderLayout());
    			pane.add(box, BorderLayout.NORTH);
    			pane.add(showButton, BorderLayout.SOUTH);
    			System.out.println("returning pane");
    			return pane;
    		}
    
    		/**
    		 * 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);
    		   
    			//Create and set up the window.
    			JFrame frame = new JFrame("VoteDialog");
    			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    
    			//Set up the content pane.
    			Container contentPane = frame.getContentPane();
    			contentPane.setLayout(new GridLayout(1,1));
    			contentPane.add(new VoteDialog(frame));
    
    			//Display the window.
    			frame.pack();
    			frame.setVisible(true);
    		}
    
    		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() {
    					createAndShowGUI();
    				}
    			});
    		}
    	}
    	
    
    Practice 9.8
    	//combo box with different window
    
    	import java.awt.*;
    	import java.awt.event.*;
    	import javax.swing.*;
    
    	public class CardWindow extends JFrame
    							implements ItemListener {
    		boolean inAnApplet = true;
    		 
    		JPanel cards;
    		final static String BUTTONPANEL = "JPanel with JButtons";
    		final static String TEXTPANEL = "JPanel with JTextField";
    
    		public CardWindow() {
    			Container contentPane = getContentPane();
    
    		 //Put the JComboBox in a JPanel to get a nicer look.
    			String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
    			JPanel cbp = new JPanel();
    			JComboBox c = new JComboBox(comboBoxItems);
    			c.setEditable(false);
    			c.addItemListener(this);
    			cbp.add(c);
    
    			//Use the default layout manager, BorderLayout
    			contentPane.add(cbp, BorderLayout.NORTH);
    
    			cards = new JPanel();
    			cards.setLayout(new CardLayout());
    	   
    			JPanel p1 = new JPanel();
    			p1.add(new JButton("Button 1"));
    			p1.add(new JButton("Button 2"));
    			p1.add(new JButton("Button 3"));
    
    			JPanel p2 = new JPanel();
    			p2.add(new JTextField("TextField", 20));
    
    			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);
    					}
    				}
    			});
    		}
    
    		public void itemStateChanged(ItemEvent evt) {
    			CardLayout cl = (CardLayout)(cards.getLayout());
    			cl.show(cards, (String)evt.getItem());
    		}
    
    		public static void main(String args[]) {
    			CardWindow window = new CardWindow();
    			window.inAnApplet = false;
    
    			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 class TabWindow extends JFrame {
    		boolean inAnApplet = true;
    		 
    		final static String BUTTONPANEL = "JPanel with JButtons";
    		final static String TEXTPANEL = "JPanel with JTextField";
    
    		public TabWindow() {
    			Container contentPane = getContentPane();
    
    			JTabbedPane tabbedPane = new JTabbedPane();
    
    			JPanel p1 = new JPanel() {
    				//Force the window to be 400+ pixels wide.
    				public Dimension getPreferredSize() {
    					Dimension size = super.getPreferredSize();
    					size.width = 400;
    					return size;
    				}
    			};
    			p1.add(new JButton("Button 1"));
    			p1.add(new JButton("Button 2"));
    			p1.add(new JButton("Button 3"));
    			tabbedPane.addTab(BUTTONPANEL, p1);
    
    			JPanel p2 = new JPanel();
    			p2.add(new JTextField("TextField", 20));
    			tabbedPane.addTab(TEXTPANEL, p2);
    
    			contentPane.add(tabbedPane, BorderLayout.CENTER);
    			
    			addWindowListener(new WindowAdapter() {
    				public void windowClosing(WindowEvent e) {
    					if (inAnApplet) {
    						dispose();
    					} else {
    						System.exit(0);
    					}
    				}
    			});
    		}
    
    		public static void main(String args[]) {
    			TabWindow window = new TabWindow();
    			window.inAnApplet = false;
    
    			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;
    
    	public class DigitalClockApplet extends JApplet {
    		ClockPanel panel;
    
    		public void init() {
    			Container contentPane=getContentPane();
    			panel = new ClockPanel(650,150);
    			panel.resize(panel.getSize());
    			contentPane.resize(panel.getSize());
    			this.resize(panel.getSize());
    			contentPane.add(panel);
    			TimeThread tt = new TimeThread(panel);
    			tt.start();
    		}
    	}
    
    
    	class ClockPanel extends JPanel
    	{
    		public JCheckBox jDate;
    		public JCheckBox jDay;
    		public JLabel jLabel1;
    		public JCheckBox jSec;
    		public boolean RUNCLOCK;
    		ClockPanel(int wid, int hgt) {
    			jLabel1 = new JLabel();
    			jDay = new JCheckBox();
    			jDate = new JCheckBox();
    			jSec = new JCheckBox();
    			this.setLayout(null);
    			this.setSize(new Dimension(wid, hgt));
    			this.setPreferredSize(new Dimension(wid, hgt));
    			this.setBounds(0, 0, wid, hgt);
    			jLabel1.setFont(new java.awt.Font("Courier 10 Pitch", 1, 24)); // NOI18N
    			jLabel1.setForeground(new java.awt.Color(71, 113, 189));
    			jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
    			jLabel1.setText("jLabel1");
    			jLabel1.setBorder(BorderFactory.createEtchedBorder());
    			this.add(jLabel1);
    			jLabel1.setBounds(30, 30, 500, 50);
    
    			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);
    			 
    		}
    	}
    
    
    	class TimeThread extends Thread implements Runnable {
    		ClockPanel cp = null;
    		private int day;
    		private String dayn;
    		private String dat;
    		private int sec;
    		private int min;
    		private int hours;
    		public TimeThread (ClockPanel cfArg) {
    			cp = cfArg;
    			cp.RUNCLOCK = true;
    		}
    
    		public void run() {
    			String dt = "";
    			while (cp.RUNCLOCK) {
    				Date date = new Date();
    				min = date.getMinutes();
    				hours = date.getHours();
    				if (cp.jDay.isSelected()) day = date.getDay();
    				else day=-1;
    				//GET DAY NAME
    				dayn="";
    				if (day!=-1) {
    					switch (day) {
    						case 0: dayn = "Sunday"; break;
    						case 1: dayn = "Monday"; break;
    						case 2: dayn = "Tuesday"; break;
    						case 3: dayn = "Wednesday"; break;
    						case 4: dayn = "Thursay"; break;
    						case 5: dayn = "Friday"; break;
    						case 6: dayn = "Saturday"; break;
    						default: dayn = "OOPS!"; break;
    					}
    				}
    				//IS DATE REQD
    				if (cp.jDate.isSelected()) dat = date.getDate() + "-" + date.getMonth() + "-" + date.getYear();
    				else dat="";
    
    				dt = dayn + " " + dat + "  " + hours + ":" + min;
    				if (cp.jSec.isSelected()) {
    					sec = date.getSeconds();
    					dt += ":" + sec + "";
    				}
    				else sec=-1;
    				//dt = date.toString();
    				cp.jLabel1.setText(dt);
    				try {
    					Thread.sleep(10);
    				} catch (InterruptedException ex) {
    					System.out.println("Exception: " + ex.toString());
    				}
    			}
    		}
    	}
    
    	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;
    
    	public class DigitalClock extends JFrame {
    		ClockPanel panel;
    		public DigitalClock() {
    			this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    			Container contentPane=this.getContentPane();
    			panel = new ClockPanel();
    			contentPane.add(panel);
    			java.awt.Dimension screenSize =    
    			java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    			this.setBounds((screenSize.width-573)/2, (screenSize.height-172)/2, 573, 172);
    		}
    
    		public static void main(String args[]) {
    			 DigitalClock dc =  new DigitalClock();
    			 dc.setVisible(true);
    			 TimeThread tt = new TimeThread(dc.panel);
    			 tt.start();
    		}
    	}
    
    
    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);
    		}
    	}
    
    	class CalculatorPanel extends JPanel
    	{
    		public CalculatorPanel()
    		{
    		setLayout(new BorderLayout());
    
    		result = 0;
    		lastCommand = "=";
    		start = true;
    
    		display = new JTextField("0.0");
    			display.setEditable(false);
    		add(display,BorderLayout.NORTH);
    
    		ActionListener insert = new InsertAction();
    		ActionListener command = new CommandAction();
    
    		panel = new JPanel();
    		panel.setLayout(new GridLayout(8,4));
    
    		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);
    		}
    
    		private void addButton(String label,ActionListener listener)
    		{
    		JButton button = new JButton(label);
    		button.addActionListener(listener);
    		panel.add(button);
    		}
    
    
    	private class InsertAction implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    		String input = event.getActionCommand();
    			if(start)
    			{
    			display.setText("");
    			start = false;
    			}
    		  if(input.equals("e"))
    			{
    			  if(display.getText().equals("-"))
    			   display.setText("-"+Math.E);
    				else
    				display.setText(""+Math.E);
    			  start=true;
    			}
    		  else if(input.equals("Pi"))
    			{
    				if(display.getText().equals("-"))
    				  display.setText("-"+Math.PI);
    				else
    				  display.setText(""+Math.PI);
    			start=true;
    			}
    		else
    			display.setText(display.getText()+input);
    		}
    	}
    
    	private class CommandAction implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
    		String command = event.getActionCommand();
    		String co = command;
    		if(co.equals("A/C"))
    			{
    			result = 0;
    			display.setText(""+result);
    			lastCommand = "=";
    			start=true;
    			}
    		else if((co.equals("+/-"))||(co.equals("Sin"))
    				  ||(co.equals("Cos"))||(co.equals("Tan"))||(co.equals("Sqrt"))
    				  ||(co.equals("n!"))||(co.equals("ln"))||(co.equals("aSin"))
    				||(co.equals("aCos"))||(co.equals("aTan"))||(co.equals("log")))
    			   {
    				lastCommand=command;
    				  calculate(Double.parseDouble(display.getText()));
    				  lastCommand="=";
    				   start=true;
    				}
    				  else if(start&&(lastCommand.equals("="))&&(result==0)
    								  &&(display.getText().equals("0.0")))
    				  {
    				if(command.equals("_"))
    				 {
    				display.setText("-");
    				start = false;
    				 }
    				else
    				  lastCommand = command;
    				 }
    		else
    				{
    			   calculate(Double.parseDouble(display.getText()));
    				 lastCommand=command;
    				 start= true;
    			}
    		}
    	}
    
    	public void calculate(double x)
    	{
    		if(lastCommand.equals("+")) result += x;
    		else if(lastCommand.equals("_")) result -= x;
    		else if(lastCommand.equals("x")) result *= x;
    		else if(lastCommand.equals("/")) result /= x;
    		else if(lastCommand.equals("+/-")) result = -x;
    		else if(lastCommand.equals("Sin")) result = Math.sin(x*Math.PI/180.0);
    		else if(lastCommand.equals("Cos")) result = Math.cos(x*Math.PI/180.0);
    		else if(lastCommand.equals("Tan")) result = Math.tan(x*Math.PI/180.0);
    		else if(lastCommand.equals("=")) result = x;
    		else if(lastCommand.equals("x^y")) result = Math.pow(result,x);
    		else if(lastCommand.equals("Sqrt")) result = Math.sqrt(x);
    		else if(lastCommand.equals("n!")) result = fact((int)x);
    		else if(lastCommand.equals("ln")) result = Math.log(x);
    		else if(lastCommand.equals("aSin")) result = Math.asin(x)*180/Math.PI;
    		else if(lastCommand.equals("aCos")) result = Math.acos(x)*180/Math.PI;
    		else if(lastCommand.equals("aTan")) result = Math.atan(x)*180/Math.PI;
    		else if(lastCommand.equals("log")) result = Math.log(x)/Math.log(10.0);
    		else if(lastCommand.equals("x^(1/y)")) result = Math.pow(result,1.0/x);
    
    		display.setText(""+result);
    	}
    
    	 private int fact(int n)
    		{
    			if((n==0)||(n==1)) return 1;
    			else return n*fact(n-1);
    		}
    
    	private JTextField display;
    	private JPanel panel;
    	private double result;
    	private String lastCommand;
    	private boolean start;
    	}
    
    	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;
    
    	public class CalcApplication {
    		public static void main(String args[]) {
    			JFrame  mainFrame = new JFrame();
    			mainFrame.setSize(400, 300);
    			Container  contentPane=mainFrame.getContentPane();
    		CalculatorPanel panel=new CalculatorPanel();
    		contentPane.add(panel);
    			mainFrame.setVisible(true);
    		}
    	}
    
    

    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 hierarchy are:
    Applet
    Dialog
    Frame
    2.General purpose containers – The intermediate containers are
    Panel
    Scroll pane
    Split pane
    Tabbed pane
    Tool bar
    3.Special purpose containers – These are intermediate containers which play specific roles in the user interface:
    Internal frame
    Layered pane
    Root pane
    4.Basic controls : The atomic components that exist primarily to get input from the user are
    Buttons
    Combo box
    List
    Menu
    Slider
    Spinner
    TextField
    5.Uneditable information displays: The atomic components which give information to the user are
    Label
    Progress bar
    Tool tip
    6.Interactive displays of highly formatted information – The atomic components that display formatted information that can be modified by the user are
    Color chooser
    File chooser
    Table
    Text
    Tree
    
    Q:
    What is the main difference between Dialog and Frame?
    A:
    In AWT, the top level window, which is itself not contained in another window, is called a FRAME.
    On the other hand, a window that appears over existing window (mostly Frame) and forces the user to respond is called a DIALOG.
    Frame f = new Frame(); // creates an object of type Frame.

    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:
    public Dialog( Frame parent, String title, boolean modal) Here:
    parent – The container to which the dialog belongs.
    title – Title of the dialog
    modal – True for modal type, false for modeless type.