Core Java -Swing

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Whereas, Now we are going to see Swing given below :

Swing in java is part of Java foundation class which is lightweight and platform independent. It is used for creating window based applications. It includes components like button, scroll bar, text field etc. Putting together all these components makes a graphical user interface, unlike AWT(Abstract Window Toolkit).

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.,

Difference Between AWT and Swing:

   S.No	                 Java AWT	                                      Java Swing
   -----    ---------------------------------------------   ---------------------------------------------------------
    1)	    AWT components are platform-dependent.          Java swing components are platform-independent.

    2)	    AWT components are heavyweight.                 Swing components are lightweight.

    3)	    AWT doesn't support pluggable look and feel.    Swing supports pluggable look and feel.

    4)	    AWT provides less components than Swing.	    Swing provides more powerful components such as 
                                                            tables, lists, scrollpanes, colorchooser, tabbedpane etc.

    5)	    AWT doesn't follows MVC(Model View Controller)  
            where model represents data, view represents    Swing follows MVC.
            presentation and controller acts as an 
            interface between model and view.	

Contents of Swing :
  • Swing UI Components
  • Swing Listeners
  • Swing Layouts

  • Hierarchy of Java Swing Class :
    swing-1

    Commonly Used Methods in Java Component Classes :
        S.No                Method	                                        Description
       ------  ------------------------------------------   -------------------------------------------------------------
        1.      public void add(Component c)                add a component on another component.
        2.      public void setSize(int width,int height)	sets size of the component.
        3.      public void setLayout(LayoutManager m)      sets the layout manager for the component.
        4.      public void setVisible(boolean b)	        sets the visibility of the component. It is by default false.
    
    
    Example program for swing :
        import javax.swing.*;  
        public class FirstSwingExample {  
          public static void main(String[] args) {  
          JFrame f=new JFrame();//creating instance of JFrame  
                  
          JButton b=new JButton("click");//creating instance of JButton  
          b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
                  
          f.add(b);//adding button in JFrame  
                  
          f.setSize(350,300);//350 width and 300 height  
          f.setLayout(null);//using no layout managers  
          f.setVisible(true);//making the frame visible  
          }  
        }  
    
    
    Output :
    swing-2

    What we will learn in Swing Tutorial
  • JLabel class
  • JButton class
  • JRadioButton class
  • JTextArea class
  • JComboBox class
  • JTable class
  • JProgressBar class
  • JSlider class
  • OpenDialog Box
  • BorderLayout
  • GridLayout
  • FlowLayout
  • SpringLayout and etc.,


  • Java JButton :
    The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed.
    Eg :
        import javax.swing.*;    
        public class ButtonExample {  
          public static void main(String[] args) {  
              JFrame f=new JFrame("Button Example");  
              JButton b=new JButton("Click Here");  
              b.setBounds(50,100,95,30);  
              f.add(b);  
              f.setSize(400,400);  
              f.setLayout(null);  
              f.setVisible(true);   
          }  
        }  
    
    
    Output :
    swing-3

    Java JButton Example with Action Listener :
    Eg:
    
      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 TesDBacademy.");  
                }  
            });  
            f.add(b);f.add(tf);  
            f.setSize(400,400);  
            f.setLayout(null);  
            f.setVisible(true);   
        }  
      }  
    
    
    Output :
    swing-4

    Java JLabel :
    The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.
    Eg:
      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);  
        }  
      }  
    
    
    Output :
    swing-5

    Java JLabel Example with ActionListener :
    Eg:
    
      import javax.swing.*;  
      import java.awt.*;  
      import java.awt.event.*;  
      public class LabelExample extends Frame implements ActionListener{  
        JTextField tf; 
        JLabel l; 
        JButton b;  
        LabelExample(){  
          tf=new JTextField();  
          tf.setBounds(50,50, 150,20);  
          l=new JLabel();  
          l.setBounds(50,100, 250,20);      
          b=new JButton("Find IP");  
          b.setBounds(50,150,95,30);  
          b.addActionListener(this);    
          add(b);add(tf);add(l);    
          setSize(400,400);  
          setLayout(null);  
          setVisible(true);   
        }  
        public void actionPerformed(ActionEvent e) {  
          try{  
          String host=tf.getText();  
          String ip=java.net.InetAddress.getByName(host).getHostAddress();  
          l.setText("IP of "+host+" is: "+ip);  
          }catch(Exception ex){
            System.out.println(ex);
          }  
        }  
        public static void main(String[] args) {  
          new LabelExample();  
        } 
      }  
    
    
    Output :
    swing-6
    Java JTextField :
    The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class.
    Eg:
      import javax.swing.*;  
      import java.awt.*;  
      import java.awt.event.*;  
      import javax.swing.*;  
      class TextFieldExample  {  
      public static void main(String args[])  {  
          JFrame f= new JFrame("TextField Example");  
          JTextField t1,t2;  
          t1=new JTextField("Welcome to Tesdbacademy...");  
          t1.setBounds(50,100, 200,30);  
          t2=new JTextField("Java TextField ");  
          t2.setBounds(50,150, 200,30);  
          f.add(t1); f.add(t2);  
          f.setSize(400,400);  
          f.setLayout(null);  
          f.setVisible(true);  
        }  
      }  
    
    
    Output :
    swing-7

    Java JTextField Example with ActionListener :
    Eg:
      import javax.swing.*;  
      import java.awt.*;  
      import java.awt.event.*;  
      import javax.swing.*;  
      class TextFieldExample  implements ActionListener {  
          JTextField tf1,tf2,tf3;  
          JButton b1,b2;  
          TextFieldExample(){  
          JFrame f= new JFrame("TextFieldExample");  
          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();  
        }
      } 
    
    
    Output :
    swing-8

    Java JTextArea :
    The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits JTextComponent class
    Eg:
      import javax.swing.*;  
      public class TextAreaExample{  
        TextAreaExample(){  
            JFrame f= new JFrame();  
            JTextArea area=new JTextArea("Welcome to Tesdbacademy");  
            area.setBounds(10,30, 200,200);  
            f.add(area);  
            f.setSize(400,400);  
            f.setLayout(null);  
            f.setVisible(true);  
        }  
        public static void main(String args[]){  
          new TextAreaExample();  
        }
      }  
    
    
    Output :
    swing-9

    Java JTextArea Example with ActionListener :
      import javax.swing.*;  
      import java.awt.event.*;  
      public class TextAreaExample implements ActionListener{  
      JLabel l1,l2;  
      JTextArea area;  
      JButton b;  
      TextAreaExample() {  
          JFrame f= new JFrame();  
          l1=new JLabel();  
          l1.setBounds(50,25,100,30);  
          l2=new JLabel();  
          l2.setBounds(160,25,100,30);  
          area=new JTextArea();  
          area.setBounds(20,75,250,200);  
          b=new JButton("Count Words");  
          b.setBounds(100,300,120,30);  
          b.addActionListener(this);  
          f.add(l1);f.add(l2);f.add(area);f.add(b);  
          f.setSize(450,450);  
          f.setLayout(null);  
          f.setVisible(true);  
      }  
      public void actionPerformed(ActionEvent e){  
          String text=area.getText();  
          String words[]=text.split("\\s");  
          l1.setText("Words: "+words.length);  
          l2.setText("Characters: "+text.length());  
      }  
      public static void main(String[] args) {  
          new TextAreaExample();  
      }  
      }  
    
    
    Output :
    swing-10

    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. Eg:
      import javax.swing.*;    
      public class PasswordFieldExample {  
        public static void main(String[] args) {    
        JFrame f=new JFrame("Password Field Example");    
        JPasswordField value = new JPasswordField();   
        JLabel l1=new JLabel("Password:");    
            l1.setBounds(20,100, 80,30);    
            value.setBounds(100,100,100,30);    
                f.add(value);  f.add(l1);  
                f.setSize(350,350);    
                f.setLayout(null);    
                f.setVisible(true);     
        }  
      }  
    
    
    Output :
    swing-11

    Java JPasswordField Example with ActionListener :
      import javax.swing.*;    
      import java.awt.event.*;  
      public class PasswordFieldExample {  
          public static void main(String[] args) {    
          JFrame f=new JFrame("Password Field Example");    
          final JLabel label = new JLabel();            
          label.setBounds(20,150, 200,50);  
          final JPasswordField value = new JPasswordField();   
          value.setBounds(100,75,100,30);   
          JLabel l1=new JLabel("Username:");    
              l1.setBounds(20,20, 80,30);    
              JLabel l2=new JLabel("Password:");    
              l2.setBounds(20,75, 80,30);    
              JButton b = new JButton("Login");  
              b.setBounds(100,120, 80,30);    
              final JTextField text = new JTextField();  
              text.setBounds(100,20, 100,30);    
                      f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);  
                      f.setSize(350,350);    
                      f.setLayout(null);    
                      f.setVisible(true);     
                      b.addActionListener(new ActionListener() {  
                        public void actionPerformed(ActionEvent e) {       
                          String data = "Username " + text.getText();  
                          data += ", Password: "   
                          + new String(value.getPassword());   
                          label.setText(data);          
                        }  
                      });   
            }  
      }  
    
    
    Output :
    swing-12

    Java JCheckBox :
    The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
    Eg:
      import javax.swing.*;    
      public class PasswordFieldExample {  
          public static void main(String[] args) {    
          JFrame f=new JFrame("Password Field Example");    
          JPasswordField value = new JPasswordField();   
          JLabel l1=new JLabel("Password:");    
              l1.setBounds(20,100, 80,30);    
              value.setBounds(100,100,100,30);    
                  f.add(value);  f.add(l1);  
                  f.setSize(350,350);    
                  f.setLayout(null);    
                  f.setVisible(true);     
          }  
      }  
    
    
    Output :
    swing-13

    Java JPasswordField Example with ActionListener :
      import javax.swing.*;    
      import java.awt.event.*;  
      public class PasswordFieldExample {  
          public static void main(String[] args) {    
          JFrame f=new JFrame("Password Field Example");    
          final JLabel label = new JLabel();            
          label.setBounds(20,150, 200,50);  
          final JPasswordField value = new JPasswordField();   
          value.setBounds(100,75,100,30);   
          JLabel l1=new JLabel("Username:");    
              l1.setBounds(20,20, 80,30);    
              JLabel l2=new JLabel("Password:");    
              l2.setBounds(20,75, 80,30);    
              JButton b = new JButton("Login");  
              b.setBounds(100,120, 80,30);    
              final JTextField text = new JTextField();  
              text.setBounds(100,20, 100,30);    
                      f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);  
                      f.setSize(350,350);    
                      f.setLayout(null);    
                      f.setVisible(true);     
                      b.addActionListener(new ActionListener() {  
                        public void actionPerformed(ActionEvent e) {       
                          String data = "Username " + text.getText();  
                          data += ", Password: "   
                          + new String(value.getPassword());   
                          label.setText(data);          
                        }  
                      });   
            }  
      } 
    
    
    Output :
    swing-14

    Java JCheckBox
    The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
    Eg:
      import javax.swing.*;  
      public class CheckBoxExample  {  
          CheckBoxExample(){  
              JFrame f= new JFrame("CheckBox Example");  
              JCheckBox checkBox1 = new JCheckBox("J2SE");  
              checkBox1.setBounds(100,100, 80,50);  
              JCheckBox checkBox2 = new JCheckBox("J2EE", true);  
              checkBox2.setBounds(100,150, 80,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();  
          }
      }  
    
    
    Output :
    swing-15

    Java JCheckBox Example with ItemListener :
      import javax.swing.*;  
      import java.awt.event.*;    
      public class CheckBoxExample{    
          CheckBoxExample(){    
              JFrame f= new JFrame("CheckBox Example");    
              final JLabel label = new JLabel();            
              label.setHorizontalAlignment(JLabel.CENTER);    
              label.setSize(400,100);    
              JCheckBox checkbox1 = new JCheckBox("J2SE");    
              checkbox1.setBounds(150,100, 80,50);    
              JCheckBox checkbox2 = new JCheckBox("J2EE");    
              checkbox2.setBounds(150,150, 80,50);    
              f.add(checkbox1); f.add(checkbox2); f.add(label);    
              checkbox1.addItemListener(new ItemListener(){    
                  public void itemStateChanged(ItemEvent e){                 
                      label.setText("J2SE Checkbox: "     
                      + (e.getStateChange()==1?"checked":"unchecked"));    
                  }    
                });    
              checkbox2.addItemListener(new ItemListener(){    
                  public void itemStateChanged(ItemEvent e){                 
                      label.setText("J2EE Checkbox: "     
                      + (e.getStateChange()==1?"checked":"unchecked"));    
                  }    
                });    
              f.setSize(400,400);    
              f.setLayout(null);    
              f.setVisible(true);    
          }    
            public static void main(String args[]){    
                new CheckBoxExample();    
            }    
      }   
    
    
    Output :
    swing-16

    Java JRadioButton :
    The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It is widely used in exam systems or quiz. It should be added in ButtonGroup to select one radio button only.
    Eg:
      import javax.swing.*;    
      public class RadioButtonExample{    
          JFrame f;    
          RadioButtonExample(){    
          f=new JFrame("RadioButton");     
          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(350,350);    
          f.setLayout(null);    
          f.setVisible(true);    
        }    
        public static void main(String[] args) {    
            new RadioButtonExample();    
        }    
      }  
    
    
    Output :
    swing-17

    Java JRadioButton Example with ActionListener :
      import javax.swing.*;    
      import java.awt.event.*;    
      class RadioButtonExample extends JFrame implements ActionListener{    
          JRadioButton rb1,rb2;    
          JButton b;    
          RadioButtonExample(){      
          rb1=new JRadioButton("Male");    
          rb1.setBounds(100,50,100,30);      
          rb2=new JRadioButton("Female");    
          rb2.setBounds(100,100,100,30);    
          ButtonGroup bg=new ButtonGroup();    
          bg.add(rb1);bg.add(rb2);    
          b=new JButton("click");    
          b.setBounds(100,150,80,30);    
          b.addActionListener(this);    
          add(rb1);add(rb2);add(b);    
          setSize(300,300);    
          setLayout(null);    
          setVisible(true);    
        }    
        public void actionPerformed(ActionEvent e){    
          if(rb1.isSelected()){    
          JOptionPane.showMessageDialog(this,"You are Male.");    
        }    
        if(rb2.isSelected()){    
          JOptionPane.showMessageDialog(this,"You are Female.");    
        }    
        }    
        public static void main(String args[]){    
        new RadioButtonExample();    
        }
      }    
    
    
    Output :
    swing-18

    Java JComboBox :
    The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits JComponent class.
    Eg:
      import javax.swing.*;    
      public class ComboBoxExample{       
      ComboBoxExample(){    
          JFrame f=new JFrame("ComboBox Example");    
          String country[]={"India","Srilanka","Afghanistan","Pakistan","Australia","South Africa","England","Newzealand"};        
          JComboBox cb=new JComboBox(country);    
          cb.setBounds(50, 50,90,20);    
          f.add(cb);        
          f.setLayout(null);    
          f.setSize(350,350);    
          f.setVisible(true);         
      }    
      public static void main(String[] args){    
          new ComboBoxExample();         
      }    
      }   
    
    
    Output :
    swing-19

    Java JComboBox Example with ActionListener :
      import javax.swing.*;    
      import java.awt.event.*;    
      public class ComboBoxExample {        
      ComboBoxExample(){    
        JFrame f=new JFrame("ComboBox Example");   
          final JLabel label = new JLabel();          
          label.setHorizontalAlignment(JLabel.CENTER);  
          label.setSize(400,100);  
          JButton b=new JButton("Show");  
          b.setBounds(200,100,75,20);  
          String languages[]={"C","C++","Java","Python"};        
          final JComboBox cb=new JComboBox(languages);    
          cb.setBounds(50, 100,90,20);    
          f.add(cb); f.add(label); f.add(b);    
          f.setLayout(null);    
          f.setSize(350,350);    
          f.setVisible(true);       
          b.addActionListener(new ActionListener() {  
              public void actionPerformed(ActionEvent e) {       
              String data = "Programming language Selected: "+ cb.getItemAt(cb.getSelectedIndex());  
              label.setText(data);  
              }  
          });           
      }    
      public static void main(String[] args) {    
          new ComboBoxExample();         
      }    
      }    
    
    
    Output :
    swing-20

    Java JTable :
    The JTable class is used to display data in tabular form. It is composed of rows and columns.
    Eg:
      import javax.swing.*;    
      public class TableExample {        
          TableExample(){    
            JFrame f=new JFrame("TableExample");    
          String data[][]={ {"1","Dhoni","870000"},    
                            {"2","Rohit","700000"},    
                            {"3","Virat","900000"}  };    
          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(350,300);    
          f.setVisible(true);    
      }     
      public static void main(String[] args) {    
          new TableExample();    
      }    
      } 
      
    
    Output :
    swing-21

    Java JTable Example with ListSelectionListener :
      import javax.swing.*;    
      import javax.swing.event.*;  
      public class TableExample {    
            public static void main(String[] a) {  
                  JFrame f = new JFrame("Table Example");  
                  String data[][]={ {"1","Dhoni","870000"},    
                                    {"2","Rohit","700000"},    
                                    {"3","Virat","900000"}  };    
                  String column[]={"ID","NAME","SALARY"};         
                  final JTable jt=new JTable(data,column);    
                  jt.setCellSelectionEnabled(true);  
                  ListSelectionModel select= jt.getSelectionModel();  
                  select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
                  select.addListSelectionListener(new ListSelectionListener() {  
                    public void valueChanged(ListSelectionEvent e) {  
                    String Data = null;  
                    int[] row = jt.getSelectedRows();  
                    int[] columns = jt.getSelectedColumns();  
                    for (int i = 0; i < row.length; i++) {  
                      for (int j = 0; j < columns.length; j++) {  
                        Data = (String) jt.getValueAt(row[i], columns[j]);  
                      } 
                    }  
                    System.out.println("Table element selected is: " + Data);    
                  }       
                });  
              JScrollPane sp=new JScrollPane(jt);    
              f.add(sp);  
              f.setSize(350,300);  
              f.setVisible(true);  
            }  
      }
    
    
    Output :
    swing-22

    If you select an element in any column, the element will be displayed on the console. For example if we click any element of Dhoni present in column name, it will displayed on the console :
      
      Table element selected is: Dhoni
    Java JList :
    The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose either one item or multiple items. It inherits JComponent class.
    Eg:
      import javax.swing.*;  
      public class ListExample  {  
          ListExample(){  
            JFrame f= new JFrame();  
            DefaultListModel l1 = new DefaultListModel<>();  
              l1.addElement("Dhoni");  
              l1.addElement("Rohit");  
              l1.addElement("Virat");  
              l1.addElement("Bumrah");  
              JList list = new JList<>(l1);  
              list.setBounds(100,100, 75,75);  
              f.add(list);  
              f.setSize(300,300);  
              f.setLayout(null);  
              f.setVisible(true);  
          }  
        public static void main(String args[])  {  
          new ListExample();  
        }
      }  
    
    
    Output :
    swing-23

    Java JList Example with ActionListener :
      import javax.swing.*;  
      import java.awt.event.*;  
      public class ListExample  {  
          ListExample(){  
              JFrame f= new JFrame();  
              final JLabel label = new JLabel();          
              label.setSize(500,100);  
              JButton b=new JButton("Show");  
              b.setBounds(200,150,80,30);  
              final DefaultListModel l1 = new DefaultListModel<>();  
                l1.addElement("C");  
                l1.addElement("C++");  
                l1.addElement("Java");  
                l1.addElement("Python");  
                final JList list1 = new JList<>(l1);  
                list1.setBounds(100,100, 75,75);  
                DefaultListModel l2 = new DefaultListModel<>();  
                l2.addElement("C Pointers");  
                l2.addElement("Control Structures");  
                l2.addElement("Swing");  
                l2.addElement("Control Flow statements");  
                final JList list2 = new JList<>(l2);  
                list2.setBounds(100,200, 75,75);  
                f.add(list1); f.add(list2); f.add(b); f.add(label);  
                f.setSize(450,450);  
                f.setLayout(null);  
                f.setVisible(true);  
                b.addActionListener(new ActionListener(){  
                    public void actionPerformed(ActionEvent e) {   
                      String data = "";  
                      if (list1.getSelectedIndex() != -1){                       
                          data = "Programming language Selected: " + list1.getSelectedValue();   
                          label.setText(data);  
                      }  
                      if(list2.getSelectedIndex() != -1){  
                          data += ", FrameWork Selected: ";  
                          for(Object frame :list2.getSelectedValues()){  
                            data += frame + " ";  
                          }  
                      }  
                      label.setText(data);  
                    }  
                });   
          }  
      public static void main(String args[]){  
        new ListExample();  
          }
        }  
    
    
    Output :
    swing-24

    Java JOptionPane :
    The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits JComponent class.
    Eg:
      import javax.swing.*;  
      public class OptionPaneExample {    
        OptionPaneExample(){  
          JFrame f=new JFrame();  
            JOptionPane.showMessageDialog(f,"Hello, Welcome to Tesdbacademy...");  
        }  
        public static void main(String[] args) {  
            new OptionPaneExample();  
        }  
      }   
    
    
    Output :
    swing-25

    Java JOptionPane Example: showMessageDialog()
      import javax.swing.*;  
      public class OptionPaneExample {    
        OptionPaneExample(){  
          JFrame f=new JFrame();  
            JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);     
        }  
        public static void main(String[] args) {  
            new OptionPaneExample();  
        }  
      }  
    
    
    Output :
    swing-26

    Java JOptionPane Example: showInputDialog()
      import javax.swing.*;  
      public class OptionPaneExample {    
        OptionPaneExample(){  
          JFrame f=new JFrame();   
            String name=JOptionPane.showInputDialog(f,"Enter Name");      
        }  
        public static void main(String[] args) {  
            new OptionPaneExample();  
        }  
      }  
    
    
    Output :
    swing-27

    Java JOptionPane Example: showConfirmDialog()
      import javax.swing.*;  
      import java.awt.event.*;  
      public class OptionPaneExample extends WindowAdapter{  
        JFrame f;  
        OptionPaneExample(){  
            f=new JFrame("OptionPaneExample");   
            f.addWindowListener(this);  
            f.setSize(350, 350);  
            f.setLayout(null);  
            f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  
            f.setVisible(true);  
        }  
        public void windowClosing(WindowEvent e) {  
            int a=JOptionPane.showConfirmDialog(f,"Are you sure?");  
        if(a==JOptionPane.YES_OPTION){  
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        }  
        }  
        public static void main(String[] args) {  
            new  OptionPaneExample();  
        }     
      }     
    
    
    Output :
    swing-28

    Java JScrollBar :
    The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a scrollbar. It inherits JComponent class.
    Eg:
      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(350,350);  
        f.setLayout(null);  
        f.setVisible(true);  
        }  
        public static void main(String args[]){  
        new ScrollBarExample();  
        }
      }  
    
    
    Output :
    swing-29

    Java JScrollBar Example with AdjustmentListener :
      import javax.swing.*;  
      import java.awt.event.*;  
      class ScrollBarExample{  
      ScrollBarExample(){  
          JFrame f= new JFrame("Scrollbar Example");  
          final JLabel label = new JLabel();          
          label.setHorizontalAlignment(JLabel.CENTER);    
          label.setSize(400,100);  
          final JScrollBar s=new JScrollBar();  
          s.setBounds(100,100, 50,100);  
          f.add(s); f.add(label);  
          f.setSize(350,350);  
        f.setLayout(null);  
        f.setVisible(true);  
        s.addAdjustmentListener(new AdjustmentListener() {  
          public void adjustmentValueChanged(AdjustmentEvent e) {  
            label.setText("Vertical Scrollbar value is:"+ s.getValue());  
          }  
      });  
      }  
      public static void main(String args[])  {  
        new ScrollBarExample();  
      }
      }  
    
    
    Output :
    swing-30

    Java JMenuBar, JMenu and JMenuItem :
    The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
    The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class.
    The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem or any of its subclass.
    Eg:
      import javax.swing.*;  
      class MenuExample{  
          JMenu menu, submenu;  
          JMenuItem i1, i2, i3, si1, si2;  
          MenuExample(){  
          JFrame f= new JFrame("Menu & 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");  
          si1=new JMenuItem("Sub-Item 1");  
          si2=new JMenuItem("Sub-Item 2");  
          menu.add(i1); menu.add(i2); menu.add(i3);  
          submenu.add(si1); submenu.add(si2);  
          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();  
          }
      }  
    
    
    Output :
    swing-31

    Example of creating Edit menu for Notepad :
      import javax.swing.*;    
      import java.awt.event.*;    
      public class MenuExample implements ActionListener{    
        JFrame f;    
        JMenuBar mb;    
        JMenu file,edit,help;    
        JMenuItem cut,copy,paste,selectAll;    
        JTextArea ta;    
        MenuExample(){    
        f=new JFrame("MenuExample with Notepad");    
        cut=new JMenuItem("cut");    
        copy=new JMenuItem("copy");    
        paste=new JMenuItem("paste");    
        selectAll=new JMenuItem("selectAll");    
          cut.addActionListener(this);    
          copy.addActionListener(this);    
          paste.addActionListener(this);    
          selectAll.addActionListener(this);    
              mb=new JMenuBar();    
              file=new JMenu("File");    
              edit=new JMenu("Edit");    
              help=new JMenu("Help");     
          edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);    
          mb.add(file);mb.add(edit);mb.add(help);    
          ta=new JTextArea();    
          ta.setBounds(5,5,360,320);    
          f.add(mb);f.add(ta);    
          f.setJMenuBar(mb);  
          f.setLayout(null);    
          f.setSize(400,400);    
          f.setVisible(true);    
        }     
        public void actionPerformed(ActionEvent e){    
        if(e.getSource()==cut)    
        ta.cut();    
        if(e.getSource()==paste)    
        ta.paste();    
        if(e.getSource()==copy)    
        ta.copy();    
        if(e.getSource()==selectAll)    
        ta.selectAll();    
        }     
        public static void main(String[] args) {    
            new MenuExample();    
        }    
      }   
    
    
    Output :
    swing-32

    Java JPopupMenu :
    PopupMenu can be dynamically popped up at specific position within a component. It inherits the JComponent class.
    Eg:
      import javax.swing.*;  
      import java.awt.event.*;  
      class PopupMenuExample  {  
          PopupMenuExample(){  
              final JFrame f= new JFrame("PopupMenu Example");  
              final JPopupMenu popupmenu = new JPopupMenu("Edit");   
              JMenuItem cut = new JMenuItem("Cut");  
              JMenuItem copy = new JMenuItem("Copy");  
              JMenuItem paste = new JMenuItem("Paste");  
              popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);        
              f.addMouseListener(new MouseAdapter() {  
                  public void mouseClicked(MouseEvent e) {              
                      popupmenu.show(f , e.getX(), e.getY());  
                  }                 
              });  
              f.add(popupmenu);   
              f.setSize(300,300);  
              f.setLayout(null);  
              f.setVisible(true);  
          }  
            public static void main(String args[])  {  
                    new PopupMenuExample();  
            }
      }  
    
    
    Output :
    swing-33

    Java JPopupMenu Example with MouseListener and ActionListener :
      import javax.swing.*;  
      import java.awt.event.*;  
      class PopupMenuExample{  
              PopupMenuExample(){  
                  final JFrame f= new JFrame("PopupMenu Example");  
                  final JLabel label = new JLabel();          
                  label.setHorizontalAlignment(JLabel.CENTER);  
                  label.setSize(400,100);  
                  final JPopupMenu popupmenu = new JPopupMenu("Edit");   
                  JMenuItem cut = new JMenuItem("Cut");  
                  JMenuItem copy = new JMenuItem("Copy");  
                  JMenuItem paste = new JMenuItem("Paste");  
                  popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);        
                  f.addMouseListener(new MouseAdapter(){  
                      public void mouseClicked(MouseEvent e){              
                          popupmenu.show(f , e.getX(), e.getY());  
                      }                 
                  });  
                  cut.addActionListener(new ActionListener(){  
                  public void actionPerformed(ActionEvent e){              
                      label.setText("cut MenuItem clicked.");  
                  }  
                  });  
                  copy.addActionListener(new ActionListener(){  
                      public void actionPerformed(ActionEvent e){              
                          label.setText("copy MenuItem clicked.");  
                      }  
                    });  
                  paste.addActionListener(new ActionListener(){  
                      public void actionPerformed(ActionEvent e){              
                          label.setText("paste MenuItem clicked.");  
                      }  
                    });  
                  f.add(label); f.add(popupmenu);   
                  f.setSize(350,350);  
                  f.setLayout(null);  
                  f.setVisible(true);  
              }  
          public static void main(String args[]){  
                  new PopupMenuExample();  
          }  
      }  
    
    
    Output :
    swing-34

    Java JCheckBoxMenuItem :
    JCheckBoxMenuItem class represents checkbox which can be included on a menu . A CheckBoxMenuItem can have text or a graphic icon or both, associated with it. MenuItem can be selected or deselected. MenuItems can be configured and controlled by actions.
    Eg:
      import java.awt.event.*;
      import javax.swing.*;   
      public class JavaCheckBoxMenuItem {  
        public static void main(final String args[]) {  
            JFrame frame = new JFrame("Jmenu Example");  
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
            JMenuBar menuBar = new JMenuBar();  
            // File Menu, F - Mnemonic  
            JMenu fileMenu = new JMenu("File");  
            fileMenu.setMnemonic(KeyEvent.VK_F);  
            menuBar.add(fileMenu);  
            // File->New, N - Mnemonic  
            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, 350);  
            frame.setVisible(true);  
        }  
      }  
    
    
    Output :
    swing-35

    Java JSeparator :
    The object of JSeparator class is used to provide a general purpose component for implementing divider lines. It is used to draw a line to separate widgets in a Layout. It inherits JComponent class.
    Eg:
      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(350,350);    
            f.setLayout(null);    
            f.setVisible(true);    
        }    
        public static void main(String args[]){    
        new SeparatorExample();    
        }
      }    
    
    
    Output :
    swing-36

    Java JSeparator Example 2 :
      import javax.swing.*;    
      import java.awt.*;  
      public class SeparatorExample{    
          public static void main(String args[]) {  
              JFrame f = new JFrame("Separator Example");      
              f.setLayout(new GridLayout(0, 1));  
              JLabel l1 = new JLabel("Above Separator");  
              f.add(l1);  
              JSeparator sep = new JSeparator();  
              f.add(sep);  
              JLabel l2 = new JLabel("Below Separator");  
              f.add(l2);  
              f.setSize(300, 200);  
              f.setVisible(true);  
          }  
      }    
    
    
    Output :
    swing-37

    Java JProgressBar :
    The JProgressBar class is used to display the progress of the task. It inherits JComponent class.
    Eg:
      import javax.swing.*;    
      public class ProgressBarExample extends JFrame{    
        JProgressBar jb;    
        int i=0,num=0;     
        ProgressBarExample(){    
        jb=new JProgressBar(0,3000);    
        jb.setBounds(40,40,160,30);         
        jb.setValue(0);    
        jb.setStringPainted(true);    
        add(jb);    
        setSize(250,150);    
        setLayout(null);    
        }    
        public void iterate(){    
          while(i<=3000){    
            jb.setValue(i);    
            i=i+20;    
            try{Thread.sleep(100);}catch(Exception e){}    
          }    
        }    
        public static void main(String[] args) {    
            ProgressBarExample m=new ProgressBarExample();    
            m.setVisible(true);    
            m.iterate();    
        }    
      }    
    
    
    Output :
    swing-38

    Java JTree :
    The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It inherits JComponent class.
    Eg:
      import javax.swing.*;  
      import javax.swing.tree.DefaultMutableTreeNode;  
      public class TreeExample {  
        TreeExample(){  
        JFrame f=new JFrame("JTree");   
          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");  
          
          DefaultMutableTreeNode font1=new DefaultMutableTreeNode("Times New Roman");  
          DefaultMutableTreeNode font2=new DefaultMutableTreeNode("Calibri");  
          DefaultMutableTreeNode font3=new DefaultMutableTreeNode("Arial Black");  
          DefaultMutableTreeNode font4=new DefaultMutableTreeNode("Verdana");  
    
          color.add(red); color.add(blue); color.add(black); color.add(green);  
          font.add(font1);font.add(font2);font.add(font3);font.add(font4);
          JTree jt=new JTree(style);  
          f.add(jt);  
          f.setSize(350,300);  
          f.setVisible(true);  
        }  
        public static void main(String[] args) {  
            new TreeExample();  
        }
      }   
    
    
    Output :
    swing-39

    Java JColorChooser Example :
      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.BLUE;    
        Color color=JColorChooser.showDialog(this,"Select a Color",initialcolor);    
        c.setBackground(color);    
        }    
            
        public static void main(String[] args) {    
            ColorChooserExample ch=new ColorChooserExample();    
            ch.setSize(300,300);    
            ch.setVisible(true);    
            ch.setDefaultCloseOperation(2);    
        }    
      } 
    
    
    Output :
    swing-40

    Java JColorChooser Example with ActionListener :
      import javax.swing.*;  
      import java.awt.*;  
      import java.awt.event.*;  
        public class ColorChooserExample extends JFrame implements ActionListener{  
        JFrame f;  
        JButton b;  
        JTextArea ta;  
        ColorChooserExample(){  
            f=new JFrame("Color Chooser Example.");  
            b=new JButton("Pad Color");  
            b.setBounds(200,250,100,30);  
            ta=new JTextArea();  
            ta.setBounds(10,10,300,200);  
            b.addActionListener(this);  
            f.add(b);f.add(ta);  
            f.setLayout(null);  
            f.setSize(400,400);  
            f.setVisible(true);  
        }  
        public void actionPerformed(ActionEvent e){  
            Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);  
            ta.setBackground(c);  
        }  
        public static void main(String[] args) {  
            new ColorChooserExample();  
        }  
      }   
    
    
    Output :
    swing-41

    Java JTabbedPane :
    The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class.
    Eg:
      import javax.swing.*;  
      public class TabbedPaneExample {    
        TabbedPaneExample(){  
          JFrame f=new JFrame("TabbedPane");   
            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();  
        }
      }  
    
    
    Output :
    swing-42

    Java JSlider with painting ticks:
    The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from a specific range.
    Eg:
      import javax.swing.*;  
      public class SliderExample1 {  
        public SliderExample1() { 
          JFrame f= new JFrame("JSlider Example");
          JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);  
          slider.setMinorTickSpacing(2);  
          slider.setMajorTickSpacing(10);  
          slider.setPaintTicks(true);  
          slider.setPaintLabels(true);  
          
          JPanel panel=new JPanel();  
          //panel.setBackground(Color.cyan);
          panel.add(slider);  
          panel.setBounds(10,50,300,50);
          f.add(panel);  
          f.setSize(350,200);  
          f.setLayout(null);  
          f.setVisible(true); 
        }  
        public static void main(String s[]) {  
          new SliderExample1();   
        }  
      }  
    
    
    Output :
    swing-43

    Java JSpinner :
    The object of JSpinner class is a single line input field that allows the user to select a number or an object value from an ordered sequence.
    Eg:
      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);     
          }  
      }  
    
    
    Output :
    swing-44

    Java JPanel :
    The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.
    It doesn't have title bar.
    Eg:
      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("JBUTTON Yellow");     
            b1.setBounds(50,100,80,30);      
            b1.setBackground(Color.yellow);      
            JButton b2=new JButton("JBUTTON Green");   
            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();  
          }  
      }  
    
    
    Output :
    swing-45

    Java JFrame :
    The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.
    Unlike Frame, JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method.
    Eg;
      import java.awt.FlowLayout;  
      import javax.swing.*;  
      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");  
            panel.add(label);  
            frame.add(panel);  
            frame.setSize(350, 200);  
            frame.setLocationRelativeTo(null);  
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
            frame.setVisible(true);  
        }  
      }  
    
    
    Output :
    swing-46


    LAYOUTS
    Java Swing Layout is an outline in the form of a user interface that has a bunch of options for creating various applications with contemporary layout selections. 'Swing' is typically used for windows application development on Java as its platform to build. There are many types of Layouts are as following given below :
    • FlowLayout
    • GridLayout
    • BorderLayout
    • SpringLayout

    Java BorderLayout :
    The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region (area) may contain one component only. It is the default layout of a frame or window. The BorderLayout provides five constants for each region:
    1. public static final int NORTH
    2. public static final int SOUTH
    3. public static final int EAST
    4. public static final int WEST
    5. public static final int CENTER
    Example of BorderLayout :
      import java.awt.*;    
      import javax.swing.*;          
      public class Border{        
        Border(){    
          JFrame f = new JFrame("Border Layout");   
              JButton b1 = new JButton("NORTH"); 
              JButton b2 = new JButton("SOUTH");  
              JButton b3 = new JButton("EAST");   
              JButton b4 = new JButton("WEST");  
              JButton b5 = new JButton("CENTER");  
                  
              f.add(b1, BorderLayout.NORTH); //b1 will be placed in North Direction    
              f.add(b2, BorderLayout.SOUTH);  //b2 will be placed in South Direction    
              f.add(b3, BorderLayout.EAST);  //b2 will be placed in East Direction    
              f.add(b4, BorderLayout.WEST);  //b2 will be placed in West Direction    
              f.add(b5, BorderLayout.CENTER);  //b2 will be placed in Center of Frame   
                  
              f.setSize(350, 350);    
              f.setVisible(true);    
        }    
        public static void main(String[] args) {    
            new Border();    
        }    
      }  
    
    
    Output :
    swing-47

    Java GridLayout :
    The Java GridLayout class is used to arrange the components in a rectangular grid. One component is displayed in each rectangle.
      import java.awt.*;    
      import javax.swing.*;        
      public class GridLayoutExample{    
        GridLayoutExample(){    
          JFrame frame = new JFrame("Grid Layout");    
            
          JButton b1 = new JButton("1");    
          JButton b2 = new JButton("2");    
          JButton b3 = new JButton("3");    
          JButton b4 = new JButton("4");    
          JButton b5 = new JButton("5");    
          JButton b6 = new JButton("6");    
          JButton b7 = new JButton("7");    
          JButton b8 = new JButton("8");    
          JButton b9 = new JButton("9");
          JButton b10 = new JButton("10"); 
          JButton b11 = new JButton("11"); 
          JButton b12 = new JButton("12");     
          
          frame.add(b1); 
          frame.add(b2); 
          frame.add(b3);  
          frame.add(b4); 
          frame.add(b5); 
          frame.add(b6);  
          frame.add(b7); 
          frame.add(b8); 
          frame.add(b9);
          frame.add(b10); 
          frame.add(b11); 
          frame.add(b12);    
                
          frame.setLayout(new GridLayout(4,3));     
          frame.setSize(350, 300);    
          frame.setVisible(true);    
        }   
        public static void main(String args[]){    
        new GridLayoutExample();    
        }    
      }   
    
    
    Output :
    swing-48

    Example of GridLayout class: Using GridLayout(int rows, int columns, int hgap, int vgap) :
      import java.awt.*;    
      import javax.swing.*;        
      public class GridLayoutExample{    
        GridLayoutExample(){    
              JFrame frame = new JFrame("Grid Layout");    
                
              JButton b1 = new JButton("1");    
              JButton b2 = new JButton("2");    
              JButton b3 = new JButton("3");    
              JButton b4 = new JButton("4");    
              JButton b5 = new JButton("5");    
              JButton b6 = new JButton("6");    
              JButton b7 = new JButton("7");    
              JButton b8 = new JButton("8");    
              JButton b9 = new JButton("9");
              JButton b10 = new JButton("10"); 
              JButton b11 = new JButton("11"); 
              JButton b12 = new JButton("12");     
              
              frame.add(b1); 
              frame.add(b2); 
              frame.add(b3);  
              frame.add(b4); 
              frame.add(b5); 
              frame.add(b6);  
              frame.add(b7); 
              frame.add(b8); 
              frame.add(b9);
              frame.add(b10); 
              frame.add(b11); 
              frame.add(b12);    
                    
              frame.setLayout(new GridLayout(4,3,20,15));     
              frame.setSize(350, 300);    
              frame.setVisible(true);    
        }    
        public static void main(String args[]){    
        new GridLayoutExample();    
        }    
      }
    
    
    Output :
    swing-49

    Java FlowLayout :
    The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is the default layout of the applet or panel.
    Fields of FlowLayout class :
    • public static final int LEFT
    • public static final int RIGHT
    • public static final int CENTER
    Example of FlowLayout class : (CENTER Alignment)
      import java.awt.*;    
      import javax.swing.*;        
      public class FlowLayoutExample{       
        FlowLayoutExample(){     
        JFrame frame = new JFrame("Flow Layout");    
    
          JButton b1 = new JButton("1");    
          JButton b2 = new JButton("2");    
          JButton b3 = new JButton("3");    
          JButton b4 = new JButton("4");    
          JButton b5 = new JButton("5");     
                  
          frame.add(b1); 
          frame.add(b2); 
          frame.add(b3); 
          frame.add(b4);      
          frame.add(b5);      
        
          frame.setLayout(new FlowLayout());    
              
          frame.setSize(500, 300);    
          frame.setVisible(true);    
        }  
        public static void main(String argvs[]){    
            new FlowLayoutExample();    
        }    
      }
    
    
    Output :
    swing-50

    Example of FlowLayout class: (RIGHT Alignment)
      import java.awt.*;    
      import javax.swing.*;        
      public class MyFlowLayout{        
        MyFlowLayout(){    
          JFrame f=new JFrame();    
                
            JButton b1=new JButton("1");    
            JButton b2=new JButton("2");    
            JButton b3=new JButton("3");    
            JButton b4=new JButton("4");    
            JButton b5=new JButton("5");    
              
            f.add(b1); 
            f.add(b2); 
            f.add(b3); 
            f.add(b4); 
            f.add(b5);   
              
            f.setLayout(new FlowLayout(FlowLayout.RIGHT));    
              
            f.setSize(500,300);    
            f.setVisible(true);    
        }    
        public static void main(String[] args) {    
            new MyFlowLayout();    
        }    
      }  
    
    
    Output :
    swing-51

    Example of FlowLayout class: (RIGHT Alignment with gap)
      import java.awt.*;    
      import javax.swing.*;    
      public class FlowLayoutExample1{     
        FlowLayoutExample1(){      
          JFrame frame = new JFrame("Flow Layout");    
              
            JButton b1 = new JButton("1");    
            JButton b2 = new JButton("2");    
            JButton b3 = new JButton("3");    
            JButton b4 = new JButton("4");    
            JButton b5 = new JButton("5");  
            JButton b6 = new JButton("6");    
            JButton b7 = new JButton("7");    
            JButton b8 = new JButton("8");    
            JButton b9 = new JButton("9");    
            JButton b10 = new JButton("10");    
                  
            frame.add(b1); 
            frame.add(b2); 
            frame.add(b3); 
            frame.add(b4);      
            frame.add(b5); 
            frame.add(b6);  
            frame.add(b7);  
            frame.add(b8);    
            frame.add(b9);  
            frame.add(b10);      
              
            frame.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));    
    
            frame.setSize(300, 300);    
            frame.setVisible(true);    
        }      
        public static void main(String argvs[]){    
            new FlowLayoutExample1();    
        }    
      }
    
    
    Output :
    swing-52

    Java SpringLayout :
    A SpringLayout arranges the children of its associated container according to a set of constraints. Constraints are nothing but horizontal and vertical distance between two-component edges. Every constraint is represented by a SpringLayout.Constraint object.
    Each child of a SpringLayout container, as well as the container itself, has exactly one set of constraints associated with them.
    Each edge position is dependent on the position of the other edge. If a constraint is added to create a new edge, than the previous binding is discarded. SpringLayout doesn't automatically set the location of the components it manages.
    Eg:
      import javax.swing.*;  
      import java.awt.*;   
      public class SpringLayoutComplete{  
        SpringLayoutComplete(){
          JFrame.setDefaultLookAndFeelDecorated(true);  
          JFrame f = new JFrame("Spring Layout");   
        
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
          f.setSize(310, 210); 
          
          Container container = f.getContentPane();  
          SpringLayout sprLayout = new SpringLayout();   
          f.setLayout(sprLayout);  
          
          Component button1 = new JButton("C++"); 
          Component button2 = new JButton("Python");   
          Component button3 = new JButton("JAVA");   
          Component button4 = new JButton("NETWORKING");  
          
          f.add(button1);   
          f.add(button2);   
          f.add(button3);   
          f.add(button4);   
          
          sprLayout.putConstraint(SpringLayout.WEST, button1,24, SpringLayout.WEST, container); 
          sprLayout.putConstraint(SpringLayout.NORTH, button1,9, SpringLayout.NORTH, container);  
          
          sprLayout.putConstraint(SpringLayout.WEST, button2,49, SpringLayout.WEST, container);  
          sprLayout.putConstraint(SpringLayout.NORTH, button2,10, SpringLayout.SOUTH, button1);  
          
          sprLayout.putConstraint(SpringLayout.WEST, button3,74, SpringLayout.WEST, container);
          sprLayout.putConstraint(SpringLayout.NORTH, button3,9, SpringLayout.SOUTH, button2);  
          
          sprLayout.putConstraint(SpringLayout.WEST, button4,9, SpringLayout.WEST, container);
          sprLayout.putConstraint(SpringLayout.NORTH, button4, 14, SpringLayout.SOUTH, button3);  
            
        f.setVisible(true);  
        }  
        public static void main(String argvs[]){  
          new SpringLayoutComplete();	
        } 
      }
    
    
    Output :
    swing-53

    (Core Java - Serialization)