Swing Components New
Swing Components New
1
OVERVIEW:
What is Swing?
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)
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.
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.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
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.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
.
Constructor Description
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.
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.
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.
16
Commonly used Constructors of
Constructor JLabel: Description
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.
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.
25
Implementing an Event Handler
ActionEvent ActionListener
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.
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
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.
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
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.
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
Constructor Description
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.
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.
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
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.
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
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
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