Unit 5 Swing
Unit 5 Swing
Listener Interfaces
o ActionListener o ItemListener o FocusListener
o KeyListener o MouseListener o MoutMotionListener
o TextListener o WindowListener, etc
Adaptor Classes
o FocusAdaptor o KeyAdaptor o MouseAdaptor o MouseMotionAdaptor
1
Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.
2
Steps to handle events:
HTML code:
3
//handling mouse events..
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=MouseEventEx width=300 height=200>
</applet>
*/
public class MouseEventEx extends Applet implements MouseListener
{
String status="";
int x=0,y=0;
public void init()
{
addMouseListener(this);
}
public void mousePressed(MouseEvent obj)
{
x=obj.getX();
y=obj.getY();
status="Mouse button pressed.";
repaint();
}
4
public void mouseEntered(MouseEvent obj)
{
x=20;
y=20;
status="Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent obj)
{
x=20;
y=20;
status="Mouse exited.";
repaint();
}
public void mouseClicked(MouseEvent obj)
{
x=25;
y=25;
showStatus("Mouse button clicked");
//status="Mouse entered.";
repaint();
}
5
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If
you inherit the adapter class, you will not be forced to provide the implementation
of all the methods of listener interfaces. So it saves code.
6
}
}
class MyAdapter extends MouseAdapter
{
AdapterEx adapter;
public MyAdapter(AdapterEx adapter)
{
this.adapter=adapter;
}
public void mouseEntered(MouseEvent obj)
{
adapter.msg="Mouse Entered.";
adapter.setBackground(Color.blue);
adapter.repaint();
}
public void mouseExited(MouseEvent obj)
{
adapter.msg="Mouse Exited.";
adapter.setBackground(Color.cyan);
adapter.repaint();
}
}
7
Java Swing
Swing Framework contains a set of classes that provides more powerful and flexible
GUI components than those of AWT. Swing provides the look and feel of modern
Java GUI. Swing library is an official Java GUI tool kit released by Sun
Microsystems. It is used to create graphical user interface with Java.
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
Features of JFC
8
AWT and Swing Hierarchy
JPanel : JPanel is Swing's version of AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly from Frame
class. The component which is added to the Frame, is refered as its Content.
JWindow : This is Swing's version of Window and has descended directly from
Window class. Like Window it uses BorderLayout by default.
JLabel : JLabel has descended from JComponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows an
icon, string or both associated with a button.
Creating a JFrame
9
1. By instantiating JFrame class.
2. By extending JFrame class.
10
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow"); //setting title of frame as MyWindow
JLabel lb = new JLabel("Welcome to My Second Window");//Creating a
label named Welcome to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close
operation.
setSize(400, 400); //setting size
setVisible(true); //setting frame visibility
}
Points To Remember
1. Import the javax.swing and java.awt package to use the classes and methods
of Swing.
2. While creating a frame (either by instantiating or extending Frame class),
following two attributes are must for visibility of the frame:
11
3. When you create objects of other components like Buttons, TextFields, etc.
Then you need to add it to the frame by using the method -
add(Component's Object);
4. You can add the following method also for resizing the frame -
setResizable(true);
JButton
JButton class provides functionality of a button. JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
It allows a button to be created using icon, a string or both. JButton supports ActionEvent. When a button
is pressed an ActionEvent is generated.
12
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JTextField
JTextField is used for taking input of single line of text. It is most widely used text
component. It has three constructors,
13
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
14
JTextArea
JPasswordField class is used to create a multiple line text input. This text area
does not display any scrollbars by default but you should use scroll panes if need it.
It has three constructors,
JTextArea()
JTextArea(int rows, int columns)
JTextArea(String text, int rows, int columns)
Here, rows and columns specify the number of rows and columns of the text area.
If the edit is false then the text in the text area can not be modified.
JPasswordField
JPasswordField creates a text field which display the disks (dots) instead of the
actual characters. It has four constructors,
JPasswordField()
JPasswordField(int length)
JPasswordField(String str)
JPasswordField(String str, int length)
Here, the length specifies the length of the password string and the str specifies the string.
The following method returns the password text entered in the password field .
String getPassword()
15
public class JPasswordFieldEx extends JApplet implements
ActionListener
{
JLabel l1,l2,l3,l4;
JTextArea text;
JPasswordField pass;
public void init()
{
Container pane=getContentPane();
pane.setLayout(new FlowLayout());
text=new JTextArea(3,15);
pass=new JPasswordField(10);
l1=new JLabel("Address");
l2=new JLabel("Password");
l3=new JLabel();
l4=new JLabel();
pane.add(l1);
pane.add(text);
pane.add(l2);
pane.add(pass);
pane.add(l3);
pane.add(l4);
pass.addActionListener(this);
}
public void actionPerformed(ActionEvent obj)
{
JPasswordField p=(JPasswordField)obj.getSource();
String password=new String(p.getPassword());
l4.setText("Your Password is : "+password);
l3.setText("Address : "+text.getText());
}
}
16
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for JCheckBox,
JCheckBox(String str)
17
JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton class is used to
create a radio button in Frames. Following is the constructor for JRadioButton,
JRadioButton(String str)
18
JComboBox
Combo box is a combination of text fields and drop-down list.JComboBox component is used to create a
combo box in Swing. Following is the constructor for JComboBox,
JComboBox(String arr[])
19
A program to change background color of a frame (Using Action Event)
import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
import java.awt.event.*; //importing event package
JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;
StColor(){
20
b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA
b5.addActionListener(this); //Registering the button with the listener
}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {
class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}
21
Ouput:
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to
the JMenuItem or any of its subclass.
22
Java JMenuItem and JMenu Example
1. import javax.swing.*;
2. class MenuExample
3. {
4. JMenu menu, submenu;
5. JMenuItem i1, i2, i3, i4, i5;
6. MenuExample(){
7. JFrame f= new JFrame("Menu and MenuItem Example");
8. JMenuBar mb=new JMenuBar();
9. menu=new JMenu("Menu");
10. submenu=new JMenu("Sub Menu");
11. i1=new JMenuItem("Item 1");
12. i2=new JMenuItem("Item 2");
13. i3=new JMenuItem("Item 3");
14. i4=new JMenuItem("Item 4");
15. i5=new JMenuItem("Item 5");
16. menu.add(i1); menu.add(i2); menu.add(i3);
17. submenu.add(i4); submenu.add(i5);
18. menu.add(submenu);
19. mb.add(menu);
20. f.setJMenuBar(mb);
21. f.setSize(400,400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25. public static void main(String args[])
26. {
27. new MenuExample();
28. }}
Output:
23
Example of creating Edit menu for Notepad:
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class MenuExample implements ActionListener{
4. JFrame f;
5. JMenuBar mb;
6. JMenu file,edit,help;
7. JMenuItem cut,copy,paste,selectAll;
8. JTextArea ta;
9. MenuExample(){
10. f=new JFrame();
11. cut=new JMenuItem("cut");
12. copy=new JMenuItem("copy");
13. paste=new JMenuItem("paste");
14. selectAll=new JMenuItem("selectAll");
15. cut.addActionListener(this);
16. copy.addActionListener(this);
17. paste.addActionListener(this);
18. selectAll.addActionListener(this);
19. mb=new JMenuBar();
20. file=new JMenu("File");
21. edit=new JMenu("Edit");
22. help=new JMenu("Help");
23. edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
24. mb.add(file);mb.add(edit);mb.add(help);
25. ta=new JTextArea();
26. ta.setBounds(5,5,360,320);
27. f.add(mb);f.add(ta);
28. f.setJMenuBar(mb);
29. f.setLayout(null);
30. f.setSize(400,400);
31. f.setVisible(true);
32. }
33. public void actionPerformed(ActionEvent e) {
34. if(e.getSource()==cut)
35. ta.cut();
36. if(e.getSource()==paste)
37. ta.paste();
38. if(e.getSource()==copy)
39. ta.copy();
40. if(e.getSource()==selectAll)
41. ta.selectAll();
42. }
43. public static void main(String[] args) {
44. new MenuExample();
45. }
46. }
24
Output:
Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a
scrollbar. It inherits JComponent class.
Constructor Description
JScrollBar() Creates a vertical scrollbar with the initial values.
Creates a scrollbar with the specified orientation and the
JScrollBar(int orientation)
initial values.
JScrollBar(int orientation, int value, int Creates a scrollbar with the specified orientation, value,
extent, int min, int max) extent, minimum, and maximum.
25
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new ScrollBarExample();
16. }}
AWT is the foundation upon which Swing is made i.e Swing is a set of GUI interfaces
that extends the AWT. But now a days AWT is merely used because most GUI Java
programs are implemented using Swing because of its rich implementation of GUI
controls and light-weighted nature.
26
Java AWT Hierarchy
Component class
Container
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar,
menu bar or border. It is container that is used for holding components.
27
Window class
Window class creates a top level window. Window does not have borders and
menubar.
Frame
Creating a Frame
28
Testawt ta = new Testawt();
}
29
Points to Remember:
There are many differences between java awt and swing that are given below.
30
//Example of AWT Controls
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="AWTControlsEx" width=300 height=500>
</applet>
*/
public class AWTControlsEx extends Applet implements ActionListener
{
Label Lname,Lpass,Lcity,Laddr,Lgender,Lmarital,Lselect,l1,l2,l3;
TextField name,pass;
TextArea addr;
Checkbox male,female,married;
CheckboxGroup gender;
Choice city;
List sel1,sel2;
Button click;
public void init()
{
Lname=new Label("Name : ");
Lpass=new Label("Password:");
Laddr=new Label("Address :");
Lcity=new Label("City :");
Lgender=new Label("Gender :");
name=new TextField(10);
pass=new TextField(10);
pass.setEchoChar('*');
addr=new TextArea("",3,20,TextArea.SCROLLBARS_BOTH);
city=new Choice();
city.add("Bhacha");
city.add("Rajkot");
city.add("Mumbai");
gender=new CheckboxGroup();
male=new Checkbox("Male",gender,true);
female=new Checkbox("Female",gender,false);
l1=new Label();
Lmarital=new Label("Marital Status :");
married=new Checkbox("Married");
click=new Button("Click Me");
l2=new Label();
Lselect=new Label("Selection is :");
sel1=new List(10);
l3=new Label();
sel2=new List();
setLayout(new GridLayout(12,2));
add(Lname);
add(name);
add(Lpass);add(pass);
31
add(Laddr);add(addr);
add(Lcity);add(city);
add(Lgender);add(male);
add(l1);add(female);
add(Lmarital);add(married);
add(click);add(l2);
add(Lselect);add(sel1);
add(l3);add(sel2);
click.addActionListener(this);
}
public void actionPerformed(ActionEvent obj)
{
sel1.add("Name : "+name.getText());
sel1.add("Password : "+pass.getText());
sel1.add("Address : "+addr.getText());
sel2.add("City : "+city.getSelectedItem());
sel2.add("Gender : "+gender.getSelectedCheckbox().getLabel());
String s=married.getState()? "Married":"Unmarried";
sel2.add("Marital Status : "+s);
}}
32