0% found this document useful (0 votes)
214 views81 pages

Swing Components New

Java Swing provides platform-independent GUI components built on top of AWT. It includes lightweight components like JButton, JTextField, JLabel etc. Swing components follow the MVC architecture. Containers like JFrame, JPanel, JDialog are used to hold and arrange Swing components using different layout managers. Common Swing components like JButton, JLabel and their usage is demonstrated in example code.

Uploaded by

M.Thenmozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
214 views81 pages

Swing Components New

Java Swing provides platform-independent GUI components built on top of AWT. It includes lightweight components like JButton, JTextField, JLabel etc. Swing components follow the MVC architecture. Containers like JFrame, JPanel, JDialog are used to hold and arrange Swing components using different layout managers. Common Swing components like JButton, JLabel and their usage is demonstrated in example code.

Uploaded by

M.Thenmozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 81

JAVA SWING

1
OVERVIEW:

What is Swing?

Java swing components

Event Handling

Layouts

2
What is java
swing
 Java Swing is a part of Java Foundation Classes (JFC) that is used
to create a Java program with a graphical user interface (GUI)

 It is built on the top of AWT (Abstract Windowing Toolkit) API and


entirely written in java.
 Java Swing provides platform-independent and lightweight
components.
 The javax.swing package provides classes for java swing API
such as JButton, JTextField, JTextArea, JRadioButton,
JCheckbox, JMenu, JColorChooser etc.
3
Difference between AWT and Swing
No. Java AWT Java Swing
AWT components are platform- Java swing components are platform-
1)
dependent. independent.
2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look Swing supports pluggable look and
and feel. feel.
Swing provides more powerful components
AWT provides less components than such as tables, lists, scrollpanes,
4) colorchooser, tabbedpane etc.
Swing.

AWT doesn't follows MVC(Model View


Controller) where model represents data,
5) view represents presentation and controller Swing follows MVC.
acts as an interface between model and
view.
4
Hierarchy of Java Swing
classes

5
The class Component is the abstract base class for the non menu user-interface
controls of Swing. Component represents an object with graphical
representation.

Commonly used Methods of Component class

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by


default false.

6
Containers
Containers are an integral part of SWING GUI components. A container
provides a space where a Jcomponent can be located. Following are
certain noticable points to be considered.
•Sub classes of Container are called as Container. For example, JPanel,
JFrame and JWindow.
•Container can add only a JComponent to itself.
•A default layout is present in each container which can be overridden
using setLayout method.

7
Top Level Containers
Every program that presents a Swing GUI contains at least one top-
level container.

A Top level container provides the support that Swing components


need to perform their painting and event-handling.

Swing provides three top-level containers:


JFrame (Main window)
JDialog (Secondary window)
JPanel
Sr.No. Container & Description
PanelJPanel is the simplest container. It provides space in which any other
1
component can be placed, including other panels.
2 FrameA JFrame is a top-level window with a title and a border.
WindowA JWindow object is a top-level window with no borders and no
3
menubar. 8
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.
.
Constructor Description

JFrame() It constructs a new frame that is initially


invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and
a blank title.
JFrame(String title) It creates a new, initially invisible Frame with
the specified title.
JFrame(String title, GraphicsConfiguration It creates a JFrame with the specified title
gc) and the specified GraphicsConfiguration of a
screen device.

9
JComponent

10
Steps to use a GUI Component

1. Create it
Instantiate object: b = new JButton(“press me”);
2. Configure it
Properties: b.text = “press me”; [avoided in java]
Methods: b.setText(“press me”);
3. Add it to the container
panel.add(b); // Frame
4. Listen to it JButton
Events: Listeners
Java
JButton
Declaration of JButton class.

public class JButton extends AbstractButton implements Access


ible

Commonly used Constructors of JButton:


Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon


object.

12
Commonly used Methods of AbstractButton
class:
Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the


button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this


object.

13
Example of displaying a button by inheritance  (Method1) 

import javax.swing.*;  
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;  
Simple2(){  
JButton b=new JButton("click");//create button  
b.setBounds(130,100,100, 40);  
          
add(b);//adding button on frame  
setSize(400,500);  
setLayout(null);  
setVisible(true);  
}  
public static void main(String[] args) {  
new Simple2();  
}
14
}  
Example of displaying image on the button: by Association
inside constructor // Method 2  
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();  
}   
15
 }    
Java
JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.

JLabel class declaration


public class JLabel extends JComponent implements SwingConstants, Accessible  

16
Commonly used Constructors of
Constructor JLabel: Description

JLabel() Creates a JLabel instance with no image and


with an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified


text.

JLabel(Icon i) Creates a JLabel instance with the specified


image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified


horizontalAlignment) text, image, and horizontal alignment.

17
Commonly used Methods of
JLabel:
Methods Description
String getText() t returns the text string that a label displays.
It defines the single line of text this
void setText(String text)
component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents
along the X axis.
Icon getIcon() It returns the graphic image that the label
displays.
It returns the alignment of the label's contents
int getHorizontalAlignment()
along the X axis.

18
mport 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);  
    }  
    }   19
Java JLabel
Example

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

JTextField class declaration

public class JTextField extends JTextComponent implements SwingConstants

21
Commonly used Constructors of JTextField :

Constructor Description
JTextField() Creates a new TextField
Creates a new TextField initialized with the
JTextField(String text)
specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the
specified text and columns.
JTextField(int columns) Creates a new empty TextField with the
specified number of columns

22
Commonly used
Methods:

Methods Description
It is used to add the specified action
void addActionListener(ActionListener l)
listener to receive action events from this
textfield.
It returns the currently set Action for this
Action getAction()
ActionEvent source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
It is used to remove the specified action
void removeActionListener(ActionListener l) listener so that it no longer receives
action events from this textfield.

23
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 Javatpoint.");
  
    t1.setBounds(50,100, 200,30);  
    t2=new JTextField("AWT Tutorial");  
    t2.setBounds(50,150, 200,30);  
    f.add(t1); f.add(t2);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);  
    }  
    }   24
Events Handling
Changing the state of an object is known as an event. For example, click on button, dragging mouse
etc. The java.awt.event package provides many event classes and Listener interfaces for event
handling.

Every time a user types a character or pushes a mouse button, an event


occurs.
Any object can be notified of an event by registering as an event
listener on the appropriate event source.
Multiple listeners can register to be notified of events of a particular
type from a particular source.

25
Implementing an Event Handler

To write an Action Listener, follow the steps given below:


1. Declare an event handler class and specify that the class either
implements an ActionListener interface or extends a class that
implements an ActionListener interface.
For example:public class MyClass implements ActionListener {

2. Register an instance of the event handler class as a listener on one


or more components.
For example:someComponent.addActionListener(instanceOfMyClass);
3. Include code that implements the methods in listener interface.
For example:public void actionPerformed(ActionEvent e) { ...//code
that reacts to the action...
26
Event and Listener (Java Event Handling)

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and


MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener 27
Registration Methods
For registering the component with the Listener, many
classes provide the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
28
Java JButton Example with ActionListener
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);   
}  
29
}  
Java JTextField
Example

30
Java
JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It allows
the editing of a single line of text. It inherits JTextField class.

JPasswordField class declaration


public class JPasswordField extends JTextField

Commonly used Constructors JPasswordField:


Constructor Description
Constructs a new JPasswordField, with a default
JPasswordField() document, null starting text string, and 0
column width.
Constructs a new empty JPasswordField with
JPasswordField(int columns)
the specified number of columns.
Constructs a new JPasswordField initialized
JPasswordField(String text)
with the specified text.
Construct a new JPasswordField initialized
JPasswordField(String text, int columns)
with the specified text and columns. 31
import javax.swing.*;    
public class PasswordFieldExample {  
    public static void main(String[] args) {    
    JFrame f=new JFrame("Password Field Examp
le");    
     JPasswordField value = new JPasswordField()
;   
     JLabel l1=new JLabel("Password:");    
        l1.setBounds(20,100, 80,30);    
         value.setBounds(100,100,100,30);    
            f.add(value);  f.add(l1);  
            f.setSize(300,300);    
            f.setLayout(null);    
            f.setVisible(true);     
}  
}  
32
Java JPasswordField Example with
ActionListene

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

34
Java
JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class

JTextArea class declaration


public class JTextArea extends JTextComponent

Commonly used Constructors of JTextArea:


Constructor Description
JTextArea() Creates a text area that displays no text initially.
Creates a text area that displays specified
JTextArea(String s)
text initially.
Creates a text area with the specified number of
JTextArea(int row, int column)
rows and columns that displays no text initially.
Creates a text area with the specified number of
JTextArea(String s, int row, int column)
rows and columns that displays specified text. 35
Commonly used Methods of JTextArea:

Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
It is used to insert the specified text on
void insert(String s, int position)
the specified position.
It is used to append the given text to the
void append(String s)
end of the document.

36
Java JTextArea Example

37
import javax.swing.*;  
public class TextAreaExample  
{  
     TextAreaExample(){  
        JFrame f= new JFrame();  
        JTextArea area=new JTextArea("Welcome t
o javatpoint");  
        area.setBounds(10,30, 200,200);  
        f.add(area);  
        f.setSize(300,300);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
   new TextAreaExample();  
    }}   38
Java
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to
"on ".It inherits JToggleButton class.

JCheckBox class declaration

public class JCheckBox extends JToggleButton implements Accessible

39
Commonly used
Constructor
Constructors:Description
Creates an initially unselected check box
JJCheckBox()
button with no text, no icon.
Creates an initially unselected check box with
JChechBox(String s)
text.
Creates a check box with text and
JCheckBox(String text, boolean selected)
specifies whether or not it is initially
selected.
Creates a check box where properties are
JCheckBox(Action a)
Commonly used taken

Methods Methods: from the Action supplied.


Description
It is used to get the
AccessibleContext getAccessibleContext()
AccessibleContext associated with
this JCheckBox.
It returns a string representation of
protected String paramString()
this JCheckBox. 40
Java JCheckBox Example with
ItemListene

41
import javax.swing.*;  
import java.awt.event.*;   public void actionPerformed(ActionEvent e){  
public class CheckBoxExample extends JFrame implements          float amount=0;  
ActionListener{           String msg="";  
    JLabel l;           if(cb1.isSelected()){  
    JCheckBox cb1,cb2,cb3;               amount+=100;  
    JButton b;               msg="Pizza: 100\n";  
    CheckBoxExample(){           }  
        l=new JLabel("Food Ordering System");           if(cb2.isSelected()){  
        l.setBounds(50,50,300,20);               amount+=30;  
        cb1=new JCheckBox("Pizza @ 100");               msg+="Burger: 30\n";  
        cb1.setBounds(100,100,150,20);           }  
        cb2=new JCheckBox("Burger @ 30");           if(cb3.isSelected()){  
        cb2.setBounds(100,150,150,20);               amount+=10;  
        cb3=new JCheckBox("Tea @ 10");               msg+="Tea: 10\n";  
        cb3.setBounds(100,200,150,20);           }  
        b=new JButton("Order");           msg+="-----------------\n";  
        b.setBounds(100,250,80,30);           JOptionPane.showMessageDialog(this,msg+"Total: "+amou
        b.addActionListener(this);   nt);  
        add(l);add(cb1);add(cb2);add(cb3);add(b);       }  
        setSize(400,400);       public static void main(String[] args) {  
        setLayout(null);           new CheckBoxExample();  
        setVisible(true);       }  
        setDefaultCloseOperation(EXIT_ON_CLOSE);   }   42
    }  
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
 It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration:

public class JRadioButton extends JToggleButton implements A


ccessible

Commonly used
Constructors of
Constructor JRadioButton: Description
Creates an unselected radio button with no
JRadioButton()
text.
Creates an unselected radio button
JRadioButton(String s)
with specified text.
Creates a radio button with the specified
JRadioButton(String s, boolean selected)
text and selected status. 43
Commonly used
Methods:

Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
It is used to set the specified Icon on
void setIcon(Icon b)
the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
It is used to add the action listener to
void addActionListener(ActionListener a)
this object.

44
Java JRadioButton Example with
ActionListene

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

46
Java
JComboBox
The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu.It inherits
JComponent class.
JComboBox class declaration
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListen
er, Accessible

Commonly used Constructors Of JComboBox:

Constructor Description

JComboBox() Creates a JComboBox with a default data


model.
JComboBox(Object[] items) Creates a JComboBox that contains the
elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the
elements in the specified Vector. 47
Commonly used Methods Of
JComboBox :
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
It is used to determine whether the
void setEditable(boolean b)
JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.

48
Java JComboBox Example with ActionListen

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

50
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows
and columns.

Commonly used Constructors of JTable:

Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

51
Java JTable
Example

52
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();    
}    
}   53
Java
JList
The object of JList class represents a list of text items. The list of text items can be
set up so that the user can choose either one item or multiple items. It inherits
JComponent class.
JList class declaration
public class JList extends JComponent implements Scrollable,
Accessibl e
Commonly used Constructors of JList
:

Constructor Description
Creates a JList with an empty, read-
JList()
only, model.
Creates a JList that displays the elements
JList(ary[] listData)
in the specified array.
Creates a JList that displays elements
JList(ListModel<ary> dataModel)
from the specified, non-null, model.

54
Commonly used Methods of
JList :
Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener(ListSelectionListener notified each time a change to the
listener) selection occurs.
It is used to return the smallest selected
int getSelectedIndex()
cell index.
It is used to return the data model that
ListModel getModel() holds a list of items displayed by the JList
component.
It is used to create a read-only ListModel
void setListData(Object[] listData)
from an array of objects.

55
Java JList Java JList Example with
Example ActionListen

56
import javax.swing.*;    f.add(list1); f.add(list2); f.add(b); f.add(label);  
import java.awt.event.*;             f.setSize(450,450);  
public class ListExample             f.setLayout(null);  
{             f.setVisible(true);  
     ListExample(){             b.addActionListener(new ActionListener() {  
        JFrame f= new JFrame();                 public void actionPerformed(ActionEvent e) {   
        final JLabel label = new JLabel();                            String data = "";  
        label.setSize(500,100);                    if (list1.getSelectedIndex() != -1) {                       
        JButton b=new JButton("Show");                       data = "Programming language Selected: " + li
        b.setBounds(200,150,80,30);   st1.getSelectedValue();   
        final DefaultListModel<String> l1 = new DefaultListModel<                     label.setText(data);  
>();                    }  
          l1.addElement("C");                    if(list2.getSelectedIndex() != -1){  
          l1.addElement("C++");                       data += ", FrameWork Selected: "+ list2.getSel
          l1.addElement("Java");   ectedValue();   ;  
          l1.addElement("PHP");                    }  
          final JList<String> list1 = new JList<>(l1);                    label.setText(data);  
          list1.setBounds(100,100, 75,75);                 }  
          DefaultListModel<String> l2 = new DefaultListModel<>();              });   
          l2.addElement("Turbo C++");        }  
          l2.addElement("Struts");   public static void main(String args[])  
          l2.addElement("Spring");       {  
          l2.addElement("YII");      new ListExample();      }}  
          final JList<String> list2 = new JList<>(l2);   57
          list2.setBounds(100,200, 75,75);  
Java
JPanel
The JPanel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the JComponents
class.
It doesn't have title bar.

JPanel class declaration


public class JPanel extends JComponent implements Accessible

58
Commonly used Constructors of
JPanel :
Constructor Description
It is used to create a new JPanel with a
JPanel()
double buffer and a flow layout.
It is used to create a new JPanel with
JPanel(boolean isDoubleBuffered) FlowLayout and the specified
buffering strategy.
It is used to create a new JPanel with
JPanel(LayoutManager layout)
the specified layout manager.

Java JPanel
Example

59
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();          }      }   60
Java JDialog
The JDialog control represents a top level window with a border
and a title used to take some form of input from the user. It
inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
Let's see the declaration for javax.swing.JDialog class.
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer  

Constructor Description

JDialog() It is used to create a


modeless dialog without a
title and without a specified
Frame owner.
JDialog(Frame owner) It is used to create a
modeless dialog with specified
Frame as its owner and an
empty title.
JDialog(Frame owner, String It is used to create a dialog
title, boolean modal) with the specified title, owner
61
Frame and modality.
62
import javax.swing.*;  
import java.awt.*;  
import java.awt.event.*;  
public class DialogExample {  
    private static JDialog d;  
    DialogExample() {  
        JFrame f= new JFrame();  
        d = new JDialog(f , "Dialog Example", true);  
        d.setLayout( new FlowLayout() );  
        JButton b = new JButton ("OK");  
 public static void main(String args[])  
        b.addActionListener ( new ActionListener()  
    {  
        {  
        new DialogExample();      }  }  
            public void actionPerformed( ActionEvent e )  
            {  
                DialogExample.d.setVisible(false);  
            }  
        });  
        d.add( new JLabel ("Click button to continue."));  
        d.add(b);   
        d.setSize(300,300);    
        d.setVisible(true);  
    }  
   
63
Java
JProgressBar
The JProgressBar class is used to display the progress of the task. It
inherits JComponent class.
JProgressBar class declaration
public class JProgressBar extends JComponent implements
SwingConstants, Ac
cessible
Commonly used Constructors:
Constructor Description
It is used to create a horizontal progress bar but
JProgressBar()
no string text.
It is used to create a horizontal progress bar
JProgressBar(int min, int max)
with the specified minimum and maximum
value.
It is used to create a progress bar with the
JProgressBar(int orient) specified orientation, it can be either Vertical or
Horizontal by using SwingConstants.VERTICAL
and SwingConstants.HORIZONTAL constants.
It is used to create a progress bar with the
JProgressBar(int orient, int min, int max) specified orientation, minimum and 64
Commonly used
Method
Methods:
Description
void setStringPainted(boolean b) It is used to determine whether string should be displayed.
void setString(String s) It is used to set value to the progress string.
It is used to set the orientation, it may be either vertical
void setOrientation(int orientation) or horizontal by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress bar.

Java JProgressBar
Example

65
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();    
}     66
Java
The Java JSlider class is used to createJSlider
the slider. By using JSlider, a user can select a value
from a specific range.

Commonly used Constructors of JSlider class

Constructor Description
creates a slider with the initial value of 50
JSlider()
and range of 0 to 100.
creates a slider with the specified orientation
JSlider(int orientation) set by either JSlider.HORIZONTAL or
JSlider.VERTICAL with the range 0 to 100 and
initial value 50.
creates a horizontal slider using the given min
JSlider(int min, int max)
and max.
creates a horizontal slider using the given
JSlider(int min, int max, int value)
min, max and value.
JSlider(int orientation, int min, int max, creates a slider using the given
67
int value) orientation, min, max and value.
Commonly used Methods of JSlider
class
Method Description
is used to set the minor tick spacing to
public void setMinorTickSpacing(int n)
the slider.
is used to set the major tick spacing to the
public void setMajorTickSpacing(int n)
slider.
is used to determine whether tick marks
public void setPaintTicks(boolean b)
are painted.
is used to determine whether labels
public void setPaintLabels(boolean b)
are painted.
publJicavvaoiJdSsiledtePraEinxtaTmrapclkes(boole i s u se d t o d e te r m i n e w h e
J a va J S il d e r E x a mp l e
: p a i
an b)
tnhteni rgtrtaci ckksis painted.

68
mport javax.swing.*;  
public class SliderExample extends JFrame{  
public SliderExample() {  
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.add(slider);  
add(panel);  
}  
public static void main(String s[]) {  
SliderExample frame=new SliderExample();  
frame.pack();  
frame.setVisible(true);  
}  
}  

69
How to change TitleBar icon in Java
Swing

70
71
Some Java Swing
Apps

Online Exam

72
Calculato
IP r
Finder

73
import javax.swing.*;    f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);  
import java.awt.event.*;           f.setSize(300,300);  
        f.setLayout(null);  
public class TextFieldExample implements ActionListener
{           f.setVisible(true);  
    JTextField tf1,tf2,tf3;       }         
    JButton b1,b2;       public void actionPerformed(ActionEvent e) {  
    TextFieldExample(){           String s1=tf1.getText();  
        JFrame f= new JFrame();           String s2=tf2.getText();  
        tf1=new JTextField();           int a=Integer.parseInt(s1);  
        tf1.setBounds(50,50,150,20);           int b=Integer.parseInt(s2);  
        tf2=new JTextField();           int c=0;  
        tf2.setBounds(50,100,150,20);           if(e.getSource()==b1){  
        tf3=new JTextField();               c=a+b;  
        tf3.setBounds(50,150,150,20);           }else if(e.getSource()==b2){  
        tf3.setEditable(false);                c=a-b;  
        b1=new JButton("+");           }  
        b1.setBounds(50,200,50,50);           String result=String.valueOf(c);  
        b2=new JButton("-");           tf3.setText(result);  
        b2.setBounds(120,200,50,50);       }  
        b1.addActionListener(this);   public static void main(String[] args) {  
        b2.addActionListener(this);       new TextFieldExample();  
        } }   74
Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner.

LayoutManager is an interface that is implemented by all the classes of layout managers.


There are following classes that represents the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
75
Java BorderLayout

The BorderLayout is used to arrange the


components in five regions: north, south, east,
west and center. Each region (area) may
contain one component only. It is the default
layout of frame or window. The BorderLayout
provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER

76
Border Layout Example

mport java.awt.*;   f.add(b1,BorderLayout.NORTH);  
import javax.swing.*;       f.add(b2,BorderLayout.SOUTH);  
       f.add(b3,BorderLayout.EAST);  
public class Border {       f.add(b4,BorderLayout.WEST);  
JFrame f;       f.add(b5,BorderLayout.CENTER);  
Border(){         
    f=new JFrame();       f.setSize(300,300);  
           f.setVisible(true);  
    JButton b1=new JButton("NORTH");;   }  
    JButton b2=new JButton("SOUTH");;   public static void main(String[] args) {  
    JButton b3=new JButton("EAST");;       new Border();  
    JButton b4=new JButton("WEST");;   }  
    JButton b5=new JButton("CENTER");;   }  
      
     77
GridLayout class

Constructors of GridLayout class


GridLayout(): creates a grid layout with one
column per component in a row.

GridLayout(int rows, int columns): creates a


grid layout with the given rows and columns
but no gaps between the components.

GridLayout(int rows, int columns, int hgap, int


vgap): creates a grid layout with the given rows
and columns alongwith given horizontal and
vertical gaps.
78
import java.awt.*;   Grid layout Example
import javax.swing.*;  
   f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
public class MyGridLayout{       f.add(b6);f.add(b7);f.add(b8);f.add(b9);  
JFrame f;     
MyGridLayout(){       f.setLayout(new GridLayout(3,3));  
    f=new JFrame();       //setting grid layout of 3 rows and 3 columns  
         
    JButton b1=new JButton("1");       f.setSize(300,300);  
    JButton b2=new JButton("2");       f.setVisible(true);  
    JButton b3=new JButton("3");   }  
    JButton b4=new JButton("4");   public static void main(String[] args) {  
    JButton b5=new JButton("5");       new MyGridLayout();  
        JButton b6=new JButton("6");   }  
        JButton b7=new JButton("7");   }  
    JButton b8=new JButton("8");  
        JButton b9=new JButton("9");   79
FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Constructors of FlowLayout class
FlowLayout(): creates a flow layout with centered
alignment and a default 5 unit horizontal and vertical
gap.
FlowLayout(int align): creates a flow layout with the
given alignment and a default 5 unit horizontal and
vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow
layout with the given alignment and the given horizontal
and vertical gap

80
Flowlayout Example
import java.awt.*;  
import javax.swing.*;  
  
public class MyFlowLayout{  
JFrame f;   f.setLayout(new FlowLayout(FlowLayout.RIGHT));
MyFlowLayout(){     
    f=new JFrame();       //setting flow layout of right alignment  
         
    JButton b1=new JButton("1");       f.setSize(300,300);  
    JButton b2=new JButton("2");       f.setVisible(true);  
    JButton b3=new JButton("3");   }  
    JButton b4=new JButton("4");   public static void main(String[] args) {  
    JButton b5=new JButton("5");       new MyFlowLayout();  
               }  
    f.add(b1);f.add(b2);f.add(b3);f.add(b4 }  
);f.add(b5);  
       81

You might also like