Java Event Handling by Implementing Actionlistener
Java Event Handling by Implementing Actionlistener
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
Output:
Java AWT Label Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
TextField tf; Label l; Button b;
LabelExample(){
tf=new TextField();
tf.setBounds(50,50, 150,20);
l=new Label();
l.setBounds(50,100, 250,20);
b=new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}
}
Output:
Output:
Output:
Java AWT Checkbox
The Checkbox 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".
Output:
Output:
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special
control for creating radio buttons in AWT.
Output:
Java AWT CheckboxGroup Example with ItemListener
1. import java.awt.*;
2. import java.awt.event.*;
3. public class CheckboxGroupExample
4. {
5. CheckboxGroupExample(){
6. Frame f= new Frame("CheckboxGroup Example");
7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
9. label.setSize(400,100);
10. CheckboxGroup cbg = new CheckboxGroup();
11. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
12. checkBox1.setBounds(100,100, 50,50);
13. Checkbox checkBox2 = new Checkbox("Java", cbg, false);
14. checkBox2.setBounds(100,150, 50,50);
15. f.add(checkBox1); f.add(checkBox2); f.add(label);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. checkBox1.addItemListener(new ItemListener() {
20. public void itemStateChanged(ItemEvent e) {
21. label.setText("C++ checkbox: Checked");
22. }
23. });
24. checkBox2.addItemListener(new ItemListener() {
25. public void itemStateChanged(ItemEvent e) {
26. label.setText("Java checkbox: Checked");
27. }
28. });
29. }
30. public static void main(String args[])
31. {
32. new CheckboxGroupExample();
33. }
34. }
Output:
Output:
Java AWT Choice Example with ActionListener
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ChoiceExample
4. {
5. ChoiceExample(){
6. Frame f= new Frame();
7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
9. label.setSize(400,100);
10. Button b=new Button("Show");
11. b.setBounds(200,100,50,20);
12. final Choice c=new Choice();
13. c.setBounds(100,100, 75,75);
14. c.add("C");
15. c.add("C++");
16. c.add("Java");
17. c.add("PHP");
18. c.add("Android");
19. f.add(c);f.add(label); f.add(b);
20. f.setSize(400,400);
21. f.setLayout(null);
22. f.setVisible(true);
23. b.addActionListener(new ActionListener() {
24. public void actionPerformed(ActionEvent e) {
25. String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());
26. label.setText(data);
27. }
28. });
29. }
30. public static void main(String args[])
31. {
32. new ChoiceExample();
33. }
34. }
Output:
Output:
Output:
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a
GUI component allows us to see invisible number of rows and columns.
Output:
Output:
Output:
Java ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in java.awt.event
package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the
registered component.
Output:
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has
five methods.
Output:
Java MouseListener Example 2
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample2 extends Frame implements MouseListener{
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
21. public static void main(String[] args) {
22. new MouseListenerExample2();
23. }
24. }
Output:
Java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package.
It has two methods.
Output:
Java ItemListener Interface
The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method: itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on
the registered checkbox component.
Output:
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package. It has three
methods.
Output:
Java KeyListener Example 2: Count Words &
Characters
1. import java.awt.*;
2. import java.awt.event.*;
3. public class KeyListenerExample extends Frame implements KeyListener{
4. Label l;
5. TextArea area;
6. KeyListenerExample(){
7.
8. l=new Label();
9. l.setBounds(20,50,200,20);
10. area=new TextArea();
11. area.setBounds(20,80,300, 300);
12. area.addKeyListener(this);
13.
14. add(l);add(area);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void keyPressed(KeyEvent e) {}
20. public void keyReleased(KeyEvent e) {
21. String text=area.getText();
22. String words[]=text.split("\\s");
23. l.setText("Words: "+words.length+" Characters:"+text.length());
24. }
25. public void keyTyped(KeyEvent e) {}
26.
27. public static void main(String[] args) {
28. new KeyListenerExample();
29. }
30. }
Output:
Java WindowListener Interface
The Java WindowListener is notified whenever you change the state of window. It is notified
against WindowEvent. The WindowListener interface is found in java.awt.event package. It
has three methods.
Output:
BorderLayout (LayoutManagers)
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:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
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:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. 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.
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample2 b=new BoxLayoutExample2();
22. }
23. }
Java CardLayout
The CardLayout class manages the components in such a manner that only one component
is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.
o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37. }
Java AWT Canvas
The Canvas control represents a blank rectangular area where the application can draw or
trap input events from the user. It inherits the Component class.