SlideShare a Scribd company logo
1
UNIT – 4
GUI & JDBC
JAVA SWING
2
OVERVIEW:
What is Swing?
Java swing components
Event Handling
Layouts
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.
4
No. Java AWT Java Swing
1)
AWT components
dependent.
are platform- 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
feel.
supports pluggable look and
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 presentation and controller
acts as an interface between model and
view.
Swing follows MVC.
Difference between AWT and Swing
5
Hierarchy of Java Swing
classes
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.
The class Component is the abstract base class for the non menu user-interface
controls of Swing. Component represents an object with graphical
representation.
7
Containers
Containers are an integral part of SWING GUI components. A container
provides a space where a component 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 Component to itself.
•A default layout is present in each container which can be overridden
using setLayout method.
8
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
1
PanelJPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.
2 FrameA JFrame is a top-level window with a title and a border.
3
WindowA JWindow object is a top-level window with no borders and no
menubar.
9
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
gc)
It creates a JFrame with the specified title
and the specified GraphicsConfiguration of a
screen device.
10
JComponent
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
Events: Listeners
JButton
12
Java
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.
Declaration of JButton class.
public class JButton extends AbstractButton implements Accessble
Commonly used Constructors of JButton:
13
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.
Commonly used Methods of AbstractButton
class:
14
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();
}
}
15
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();
}
}
16
Theobjectof JLabelclassisa componentfor placingtextina container.Itis usedto displaya
single line of read only text. The text can be changed by an applicationbut a user cannot
edititdirectly.ItinheritsJComponent class.
Java
JLabel
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants, Accessible
17
Constructor 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
horizontalAlignment)
Creates a JLabel instance with the specified
text, image, and horizontal alignment.
Commonly used Constructors of
JLabel:
18
Methods Description
String getText() It returns the text string that a label displays.
void setText(String text)
It defines the single line of text this
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.
int getHorizontalAlignment()
It returns the alignment of the label's contents
along the X axis.
Commonly used Methods of
JLabel:
19
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);
}
}
20
Java JLabel
Example
21
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
22
Commonly used Constructors of JTextField :
Constructor Description
JTextField() Creates a new TextField
JTextField(String text)
Creates a new TextField initialized with the
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
23
Commonly used
Methods:
Methods Description
void addActionListener(ActionListener l)
It is used to add the specified action listener to
receive action events from this textfield.
Action getAction()
It returns the currently set Action for this
ActionEvent source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener l)
It is used to remove the specified action listener
so that it no longer receives action events from
this textfield.
24
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);
}
}
25
Events 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.
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.
26
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...
27
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
28
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){}
29
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);
}
}
30
Java JTextField
Example
31
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener
{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
} }
32
Java
JPasswordField
Constructor Description
JPasswordField()
Constructs a new JPasswordField, with a
default document, null starting text string,
and 0 column width.
JPasswordField(int columns)
Constructs a new empty JPasswordField with
the specified number of columns.
JPasswordField(String text)
Constructs a new JPasswordField initialized
with the specified text.
JPasswordField(String text, int columns)
Construct a new JPasswordField initialized
with the specified text and columns.
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:
33
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);
}
}
34
Java JPasswordField Example with
ActionListene
35
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.a
dd(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
});
}
}
36
Java
JTextArea
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s)
Creates a text area that displays specified
text initially.
JTextArea(int row
, int column)
Creates a text area with the specified number of
rows and columnsthat displays no text initially.
JTextArea(String s, int row
, int column)
Creates a text area with thespecifiednumber of
rows and columnsthat displays specified text.
The object of a JT
extArea 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:
37
Commonly used Methods of JTextArea:
Methods Description
void setRows(int rows) It is used to set specifiednumber of rows.
void setColumns(int cols) It is used to set specifiednumber of columns.
void setFont(Font f) It is used to set thespecified font.
void insert(String s, int position)
It is used to insert thespecified text on
the specified position.
void append(String s)
It is used to append the given text to the
end of the document.
38
Java JTextArea Example
39
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to our university");
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();
}}
40
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
Constructor Description
JJCheckBox()
Creates an initially unselected check box
button with no text, no icon.
JChechBox(String s)
Creates an initially unselected check box with
text.
JCheckBox(String text, boolean selected)
Creates a check box with text and specifies
whether or not it is initially selected.
JCheckBox(Action a)
Creates a check box where properties are taken
from the Action supplied.
Methods Description
AccessibleContext getAccessibleContext()
It is used to get the AccessibleContext
associated with this JCheckBox.
protected String paramString()
It returns a string representation of this
JCheckBox.
Commonly used
Constructors:
Commonly used
Methods:
Java JCheckBox Example with
ItemListene
43
import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample extends JFrame implements
ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30n";
}
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10n";
}
msg+="-----------------n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample();
}
}
44
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
Accessible
Commonly used Constructors of
JRadioButton:
Constructor Description
JRadioButton()
Creates an unselected radio button with no
text.
JRadioButton(String s)
Creates an unselected radio button
with specified text.
JRadioButton(String s, boolean selected)
Creates a radio button with thespecified text
and selected status.
45
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.
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.
46
Java JRadioButton Example with ActionListener
47
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame impleme
nts 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();
}}
Java
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.
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 JComboBoxextends JComponent implements ItemSelectable, ListDataListener,ActionListener,
Accessible
Commonly used Constructors Of JComboBox:
49
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.
void setEditable(boolean b)
It is used to determine whether the
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.
Commonly used Methods Of
JComboBox :
50
Java JComboBox Example with ActionListener
51
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
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+
+","C#","Java","PHP"};
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();
}
}
52
Java JTable
The JTable class is used to displaydatain 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.
53
Java JTable
Example
54
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();
}
}
55
Java
JList
The object of JList class represents a list of text items. The list of text items can be
set up so thatthe 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
JList()
Creates a JList with an empty, read-only,
model.
JList(ary[] listData)
Creates a JList that displays the elements in
the specified array.
JList(ListModel<ary> dataModel)
Creates a JList that displays elements from
the specified, non-null, model.
56
Commonly used Methods of
JList :
Methods Description
Void
addListSelectionListener(ListSelectionListener
listener)
It is used to add a listener to the list, to be
notified each time a change to the
selection occurs.
int getSelectedIndex()
It is used to return the smallest selected
cell index.
ListModel getModel()
It is used to return the datamodel that
holds a list of items displayed by the JList
component.
void setListData(Object[] listData)
It is used to create a read-only ListModel
from anarray of objects.
57
Java JList Example with
ActionListen
Java JList
Example
58
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<String> l1 = new DefaultListModel<
>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
final JList<String> list1 = new JList<>(l1);
list1.setBounds(100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
l2.addElement("Turbo C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
final JList<String> 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: " + li
st1.getSelectedValue();
label.setText(data);
}
if(list2.getSelectedIndex() != -1){
data += ", FrameWork Selected: "+ list2.getSel
ectedValue(); ;
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample(); }}
59
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
Commonly used Constructors of
JPanel :
Constructor Description
JPanel()
It is used to create a new JPanel with a
double buffer and a flow layout.
JPanel(boolean isDoubleBuffered)
It is used to create a new JPanel with
FlowLayout and the specified
buffering strategy
.
JPanel(LayoutManager layout)
It is used to create a new JPanel with
the specified layout manager.
Java JPanel
Example
61
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(); } }
62
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
title, boolean modal)
It is used to create a dialog
with the specified title, owner
Frame and modality.
63
64
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");
b.addActionListener ( new ActionListener()
{
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);
}
public static void main(String args[])
{
new DialogExample(); } }
65
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
JProgressBar()
It is used to create a horizontal progress bar but no
string text.
JProgressBar(int min, int max)
It is used to create a horizontal progress bar with
the specified minimum and maximum value.
JProgressBar(int orient)
It is used to create a progress bar with the specified
orientation, it can be either Vertical or Horizontal by
using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int orient, int min, int max)
It is used to create a progress bar with the
specified orientation, minimum and maximum
value.
Commonly used
Methods:
Method 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.
void setOrientation(int orientation)
It is used to set the orientation, it may be either vertical 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
67
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();
}
}
68
Java
JSlider
The Java JSlider class is used to create the slider. By using JSlider, a user can select a value
from a specific range.
Commonly used Constructors of JSlider class
Constructor Description
JSlider()
creates a slider with the initial value of 50 and
range of 0 to 100.
JSlider(int orientation)
creates a slider with the specified orientation
set by either JSlider.HORIZONTAL or
JSlider.VERTICAL with the range 0 to 100 and
initial value 50.
JSlider(int min, int max)
creates a horizontal slider using the given min
and max.
JSlider(int min, int max, int value)
creates a horizontal slider using the given min,
max and value.
JSlider(int orientation, int min, int max, int
value)
creates a slider using the given orientation,
min, max and value.
69
Commonly used Methods of JSlider
class
Method Description
public void setMinorTickSpacing(int n)
is used to set the minor tick spacing to the
slider.
public void setMajorTickSpacing(int n)
is used to set the major tick spacing to the
slider.
public void setPaintTicks(boolean b)
is used to determine whether tick marks are
painted.
public void setPaintLabels(boolean b)
is used to determine whether labels are
painted.
public void setPaintTracks(boolean b) is used to determine whether track is
painted
Java JSlider Example
Java JSlider Example: painting ticks
70
import 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);
}
}
71
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.
72
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
73
Border Layout Example
mport java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
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);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
74
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.
75
Grid layout Example
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
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");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
76
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
77
Flowlayout Example
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
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));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
How to change TitleBar icon in Java
Swing
Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER
80
Some Java Swing
Apps
Online Exam
81
IP
Finder
Calculato
r

More Related Content

Similar to Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER (20)

DOC
java swing notes in easy manner for UG students
RameshPrasadBhatta2
 
PPTX
Swing component point are mentioned in PPT which helpgul for creating Java GU...
sonalipatil225940
 
PPT
03_GUI.ppt
DrDGayathriDevi
 
PPT
28 awt
Prachi Vijh
 
PPT
13457272.ppt
aptechaligarh
 
PPTX
MODULE 5.pptx gui programming and applets
LIKITHLIKITH7
 
PPTX
Advanced Java GUI Programming_ AWT, Swing, and Event Handling_AI PPT Maker.pptx
tarunsocsa
 
PPT
L11cs2110sp13
karan saini
 
PPTX
Computer Programming NC III - Java Swing.pptx
jonathancapitulo2
 
PPTX
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
PPTX
Awt, Swing, Layout managers
swapnac12
 
PPT
2.swing.ppt advance java programming 3rd year
YugandharaNalavade
 
PPTX
Java Swing Presentation made by aarav patel
AaravPatel40
 
PPT
Chapter11 graphical components
Arifa Fatima
 
PPTX
Java_Unit6pptx__2024_04_13_18_18_07.pptx
lakhatariyajaimin09
 
PPTX
UNIT 2 SWIGS for java programing by .pptx
st5617067
 
PPT
Chap1 1 1
Hemo Chella
 
PPT
Chap1 1.1
Hemo Chella
 
PPT
Graphic User Interface (GUI) Presentation
riham585503
 
PDF
DSJ_Unit III.pdf
Arumugam90
 
java swing notes in easy manner for UG students
RameshPrasadBhatta2
 
Swing component point are mentioned in PPT which helpgul for creating Java GU...
sonalipatil225940
 
03_GUI.ppt
DrDGayathriDevi
 
28 awt
Prachi Vijh
 
13457272.ppt
aptechaligarh
 
MODULE 5.pptx gui programming and applets
LIKITHLIKITH7
 
Advanced Java GUI Programming_ AWT, Swing, and Event Handling_AI PPT Maker.pptx
tarunsocsa
 
L11cs2110sp13
karan saini
 
Computer Programming NC III - Java Swing.pptx
jonathancapitulo2
 
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
Awt, Swing, Layout managers
swapnac12
 
2.swing.ppt advance java programming 3rd year
YugandharaNalavade
 
Java Swing Presentation made by aarav patel
AaravPatel40
 
Chapter11 graphical components
Arifa Fatima
 
Java_Unit6pptx__2024_04_13_18_18_07.pptx
lakhatariyajaimin09
 
UNIT 2 SWIGS for java programing by .pptx
st5617067
 
Chap1 1 1
Hemo Chella
 
Chap1 1.1
Hemo Chella
 
Graphic User Interface (GUI) Presentation
riham585503
 
DSJ_Unit III.pdf
Arumugam90
 

Recently uploaded (20)

PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
community health nursing question paper 2.pdf
Prince kumar
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Dimensions of Societal Planning in Commonism
StefanMz
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Ad

Unit 4_1.pptx JDBC AND GUI FOR CLIENT SERVER

  • 1. 1 UNIT – 4 GUI & JDBC JAVA SWING
  • 2. 2 OVERVIEW: What is Swing? Java swing components Event Handling Layouts
  • 3. 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.
  • 4. 4 No. Java AWT Java Swing 1) AWT components dependent. are platform- 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 feel. supports pluggable look and 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 presentation and controller acts as an interface between model and view. Swing follows MVC. Difference between AWT and Swing
  • 5. 5 Hierarchy of Java Swing classes
  • 6. 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. The class Component is the abstract base class for the non menu user-interface controls of Swing. Component represents an object with graphical representation.
  • 7. 7 Containers Containers are an integral part of SWING GUI components. A container provides a space where a component 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 Component to itself. •A default layout is present in each container which can be overridden using setLayout method.
  • 8. 8 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 1 PanelJPanel is the simplest container. It provides space in which any other component can be placed, including other panels. 2 FrameA JFrame is a top-level window with a title and a border. 3 WindowA JWindow object is a top-level window with no borders and no menubar.
  • 9. 9 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 gc) It creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.
  • 11. 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 Events: Listeners JButton
  • 12. 12 Java 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. Declaration of JButton class. public class JButton extends AbstractButton implements Accessble Commonly used Constructors of JButton:
  • 13. 13 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. Commonly used Methods of AbstractButton class:
  • 14. 14 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(); } }
  • 15. 15 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(); } }
  • 16. 16 Theobjectof JLabelclassisa componentfor placingtextina container.Itis usedto displaya single line of read only text. The text can be changed by an applicationbut a user cannot edititdirectly.ItinheritsJComponent class. Java JLabel JLabel class declaration public class JLabel extends JComponent implements SwingConstants, Accessible
  • 17. 17 Constructor 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 horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. Commonly used Constructors of JLabel:
  • 18. 18 Methods Description String getText() It returns the text string that a label displays. void setText(String text) It defines the single line of text this 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. int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis. Commonly used Methods of JLabel:
  • 19. 19 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); } }
  • 21. 21 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
  • 22. 22 Commonly used Constructors of JTextField : Constructor Description JTextField() Creates a new TextField JTextField(String text) Creates a new TextField initialized with the 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
  • 23. 23 Commonly used Methods: Methods Description void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events from this textfield. Action getAction() It returns the currently set Action for this ActionEvent source, or null if no Action is set. void setFont(Font f) It is used to set the current font. void removeActionListener(ActionListener l) It is used to remove the specified action listener so that it no longer receives action events from this textfield.
  • 24. 24 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); } }
  • 25. 25 Events 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. 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.
  • 26. 26 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...
  • 27. 27 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
  • 28. 28 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){}
  • 29. 29 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); } }
  • 31. 31 import javax.swing.*; import java.awt.event.*; public class TextFieldExample implements ActionListener { JTextField tf1,tf2,tf3; JButton b1,b2; TextFieldExample(){ JFrame f= new JFrame(); tf1=new JTextField(); tf1.setBounds(50,50,150,20); tf2=new JTextField(); tf2.setBounds(50,100,150,20); tf3=new JTextField(); tf3.setBounds(50,150,150,20); tf3.setEditable(false); b1=new JButton("+"); b1.setBounds(50,200,50,50); b2=new JButton("-"); b2.setBounds(120,200,50,50); b1.addActionListener(this); b2.addActionListener(this); f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void actionPerformed(ActionEvent e) { String s1=tf1.getText(); String s2=tf2.getText(); int a=Integer.parseInt(s1); int b=Integer.parseInt(s2); int c=0; if(e.getSource()==b1){ c=a+b; }else if(e.getSource()==b2){ c=a-b; } String result=String.valueOf(c); tf3.setText(result); } public static void main(String[] args) { new TextFieldExample(); } }
  • 32. 32 Java JPasswordField Constructor Description JPasswordField() Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width. JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns. JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text. JPasswordField(String text, int columns) Construct a new JPasswordField initialized with the specified text and columns. 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:
  • 33. 33 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); } }
  • 34. 34 Java JPasswordField Example with ActionListene
  • 35. 35 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.a dd(text); f.setSize(300,300); f.setLayout(null); f.setVisible(true); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = "Username " + text.getText(); data += ", Password: " + new String(value.getPassword()); label.setText(data); } }); } }
  • 36. 36 Java JTextArea Constructor Description JTextArea() Creates a text area that displays no text initially. JTextArea(String s) Creates a text area that displays specified text initially. JTextArea(int row , int column) Creates a text area with the specified number of rows and columnsthat displays no text initially. JTextArea(String s, int row , int column) Creates a text area with thespecifiednumber of rows and columnsthat displays specified text. The object of a JT extArea 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:
  • 37. 37 Commonly used Methods of JTextArea: Methods Description void setRows(int rows) It is used to set specifiednumber of rows. void setColumns(int cols) It is used to set specifiednumber of columns. void setFont(Font f) It is used to set thespecified font. void insert(String s, int position) It is used to insert thespecified text on the specified position. void append(String s) It is used to append the given text to the end of the document.
  • 39. 39 import javax.swing.*; public class TextAreaExample { TextAreaExample(){ JFrame f= new JFrame(); JTextArea area=new JTextArea("Welcome to our university"); 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(); }}
  • 40. 40 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
  • 41. Constructor Description JJCheckBox() Creates an initially unselected check box button with no text, no icon. JChechBox(String s) Creates an initially unselected check box with text. JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied. Methods Description AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this JCheckBox. protected String paramString() It returns a string representation of this JCheckBox. Commonly used Constructors: Commonly used Methods:
  • 42. Java JCheckBox Example with ItemListene
  • 43. 43 import javax.swing.*; import java.awt.event.*; public class CheckBoxExample extends JFrame implements ActionListener{ JLabel l; JCheckBox cb1,cb2,cb3; JButton b; CheckBoxExample(){ l=new JLabel("Food Ordering System"); l.setBounds(50,50,300,20); cb1=new JCheckBox("Pizza @ 100"); cb1.setBounds(100,100,150,20); cb2=new JCheckBox("Burger @ 30"); cb2.setBounds(100,150,150,20); cb3=new JCheckBox("Tea @ 10"); cb3.setBounds(100,200,150,20); b=new JButton("Order"); b.setBounds(100,250,80,30); b.addActionListener(this); add(l);add(cb1);add(cb2);add(cb3);add(b); setSize(400,400); setLayout(null); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e){ float amount=0; String msg=""; if(cb1.isSelected()){ amount+=100; msg="Pizza: 100n"; } if(cb2.isSelected()){ amount+=30; msg+="Burger: 30n"; } if(cb3.isSelected()){ amount+=10; msg+="Tea: 10n"; } msg+="-----------------n"; JOptionPane.showMessageDialog(this,msg+"Total: "+amount); } public static void main(String[] args) { new CheckBoxExample(); } }
  • 44. 44 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 Accessible Commonly used Constructors of JRadioButton: Constructor Description JRadioButton() Creates an unselected radio button with no text. JRadioButton(String s) Creates an unselected radio button with specified text. JRadioButton(String s, boolean selected) Creates a radio button with thespecified text and selected status.
  • 45. 45 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. 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.
  • 46. 46 Java JRadioButton Example with ActionListener
  • 47. 47 import javax.swing.*; import java.awt.event.*; class RadioButtonExample extends JFrame impleme nts 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(); }}
  • 48. Java 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. 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 JComboBoxextends JComponent implements ItemSelectable, ListDataListener,ActionListener, Accessible Commonly used Constructors Of JComboBox:
  • 49. 49 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. void setEditable(boolean b) It is used to determine whether the 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. Commonly used Methods Of JComboBox :
  • 50. 50 Java JComboBox Example with ActionListener
  • 51. 51 import javax.swing.*; import java.awt.event.*; public class ComboBoxExample { JFrame f; ComboBoxExample(){ 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+ +","C#","Java","PHP"}; 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(); } }
  • 52. 52 Java JTable The JTable class is used to displaydatain 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.
  • 54. 54 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(); } }
  • 55. 55 Java JList The object of JList class represents a list of text items. The list of text items can be set up so thatthe 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 JList() Creates a JList with an empty, read-only, model. JList(ary[] listData) Creates a JList that displays the elements in the specified array. JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.
  • 56. 56 Commonly used Methods of JList : Methods Description Void addListSelectionListener(ListSelectionListener listener) It is used to add a listener to the list, to be notified each time a change to the selection occurs. int getSelectedIndex() It is used to return the smallest selected cell index. ListModel getModel() It is used to return the datamodel that holds a list of items displayed by the JList component. void setListData(Object[] listData) It is used to create a read-only ListModel from anarray of objects.
  • 57. 57 Java JList Example with ActionListen Java JList Example
  • 58. 58 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<String> l1 = new DefaultListModel< >(); l1.addElement("C"); l1.addElement("C++"); l1.addElement("Java"); l1.addElement("PHP"); final JList<String> list1 = new JList<>(l1); list1.setBounds(100,100, 75,75); DefaultListModel<String> l2 = new DefaultListModel<>(); l2.addElement("Turbo C++"); l2.addElement("Struts"); l2.addElement("Spring"); l2.addElement("YII"); final JList<String> 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: " + li st1.getSelectedValue(); label.setText(data); } if(list2.getSelectedIndex() != -1){ data += ", FrameWork Selected: "+ list2.getSel ectedValue(); ; } label.setText(data); } }); } public static void main(String args[]) { new ListExample(); }}
  • 59. 59 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
  • 60. Commonly used Constructors of JPanel : Constructor Description JPanel() It is used to create a new JPanel with a double buffer and a flow layout. JPanel(boolean isDoubleBuffered) It is used to create a new JPanel with FlowLayout and the specified buffering strategy . JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager. Java JPanel Example
  • 61. 61 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(); } }
  • 62. 62 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 title, boolean modal) It is used to create a dialog with the specified title, owner Frame and modality.
  • 63. 63
  • 64. 64 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"); b.addActionListener ( new ActionListener() { 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); } public static void main(String args[]) { new DialogExample(); } }
  • 65. 65 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 JProgressBar() It is used to create a horizontal progress bar but no string text. JProgressBar(int min, int max) It is used to create a horizontal progress bar with the specified minimum and maximum value. JProgressBar(int orient) It is used to create a progress bar with the specified orientation, it can be either Vertical or Horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants. JProgressBar(int orient, int min, int max) It is used to create a progress bar with the specified orientation, minimum and maximum value.
  • 66. Commonly used Methods: Method 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. void setOrientation(int orientation) It is used to set the orientation, it may be either vertical 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
  • 67. 67 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(); } }
  • 68. 68 Java JSlider The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from a specific range. Commonly used Constructors of JSlider class Constructor Description JSlider() creates a slider with the initial value of 50 and range of 0 to 100. JSlider(int orientation) creates a slider with the specified orientation set by either JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50. JSlider(int min, int max) creates a horizontal slider using the given min and max. JSlider(int min, int max, int value) creates a horizontal slider using the given min, max and value. JSlider(int orientation, int min, int max, int value) creates a slider using the given orientation, min, max and value.
  • 69. 69 Commonly used Methods of JSlider class Method Description public void setMinorTickSpacing(int n) is used to set the minor tick spacing to the slider. public void setMajorTickSpacing(int n) is used to set the major tick spacing to the slider. public void setPaintTicks(boolean b) is used to determine whether tick marks are painted. public void setPaintLabels(boolean b) is used to determine whether labels are painted. public void setPaintTracks(boolean b) is used to determine whether track is painted Java JSlider Example Java JSlider Example: painting ticks
  • 70. 70 import 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); } }
  • 71. 71 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.
  • 72. 72 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
  • 73. 73 Border Layout Example mport java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); 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); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } }
  • 74. 74 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.
  • 75. 75 Grid layout Example import java.awt.*; import javax.swing.*; public class MyGridLayout{ JFrame f; MyGridLayout(){ 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"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyGridLayout(); } }
  • 76. 76 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
  • 77. 77 Flowlayout Example import java.awt.*; import javax.swing.*; public class MyFlowLayout{ JFrame f; MyFlowLayout(){ 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)); //setting flow layout of right alignment f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyFlowLayout(); } }
  • 78. How to change TitleBar icon in Java Swing