0% found this document useful (0 votes)
225 views53 pages

Java Event Handling by Implementing Actionlistener

1. The document discusses three ways to implement event handling in Java: within the class, in another class, or using an anonymous class. 2. It provides code examples for each approach, demonstrating how to add an action listener and handle button click events. 3. The last part describes some common AWT components like labels, text fields, text areas, checkboxes, and checkbox groups, along with basic code examples of how to use them.

Uploaded by

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

Java Event Handling by Implementing Actionlistener

1. The document discusses three ways to implement event handling in Java: within the class, in another class, or using an anonymous class. 2. It provides code examples for each approach, demonstrating how to add an action listener and handle button click events. 3. The last part describes some common AWT components like labels, text fields, text areas, checkboxes, and checkbox groups, along with basic code examples of how to use them.

Uploaded by

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

Java Event Handling Code

We can put the event handling code into one of the following places:
1. Within class

2. Other class

3. Anonymous class

Java event handling by implementing ActionListener

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

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield etc.

2) Java event handling by outer class

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");
}
}

3) Java event handling by anonymous class

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();
}
}

Java AWT Label


The object of Label class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible

Java Label Example


1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4. Frame f= new Frame("Label Example");
5. Label l1,l2;
6. l1=new Label("First Label.");
7. l1.setBounds(50,100, 100,30);
8. l2=new Label("Second Label.");
9. l2.setBounds(50,150, 100,30);
10. f.add(l1); f.add(l2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }

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:

Java AWT TextField


The object of a TextField class is a text component that allows the editing of a single line
text. It inherits TextComponent class.

AWT TextField Class Declaration


1. public class TextField extends TextComponent

Java AWT TextField Example


import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java AWT TextField Example with ActionListener


import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
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();
}
}
Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the editing
of multiple line text. It inherits TextComponent class.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent

Java AWT TextArea Example


import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Java AWT TextArea Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample extends Frame implements ActionListener{
Label l1,l2;
TextArea area;
Button b;
TextAreaExample(){
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
area=new TextArea();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);add(l2);add(area);add(b);
setSize(400,450);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}

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".

AWT Checkbox Class Declaration


1. public class Checkbox extends Component implements ItemSelectable, Accessible

Java AWT Checkbox Example


import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}

Output:

Java AWT Checkbox Example with ItemListener


import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}

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.

AWT CheckboxGroup Class Declaration


1. public class CheckboxGroup extends Object implements Serializable

Java AWT CheckboxGroup Example


1. import java.awt.*;
2. public class CheckboxGroupExample
3. {
4. CheckboxGroupExample(){
5. Frame f= new Frame("CheckboxGroup Example");
6. CheckboxGroup cbg = new CheckboxGroup();
7. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
8. checkBox1.setBounds(100,100, 50,50);
9. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
10. checkBox2.setBounds(100,150, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }

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:

Java AWT Choice


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 Component class.

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible

Java AWT Choice Example


1. import java.awt.*;
2. public class ChoiceExample
3. {
4. ChoiceExample(){
5. Frame f= new Frame();
6. Choice c=new Choice();
7. c.setBounds(100,100, 75,75);
8. c.add("Item 1");
9. c.add("Item 2");
10. c.add("Item 3");
11. c.add("Item 4");
12. c.add("Item 5");
13. f.add(c);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ChoiceExample();
21. }
22. }

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:

Java AWT List


The object of List class represents a list of text items. By the help of list, user can choose
either one item or multiple items. It inherits Component class.

AWT List class Declaration


1. public class List extends Component implements ItemSelectable, Accessible

Java AWT List Example


1. import java.awt.*;
2. public class ListExample
3. {
4. ListExample(){
5. Frame f= new Frame();
6. List l1=new List(5);
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
10. l1.add("Item 3");
11. l1.add("Item 4");
12. l1.add("Item 5");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }
22. }

Output:

Java AWT List Example with ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. public class ListExample
4. {
5. ListExample(){
6. Frame f= new Frame();
7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
9. label.setSize(500,100);
10. Button b=new Button("Show");
11. b.setBounds(200,150,80,30);
12. final List l1=new List(4, false);
13. l1.setBounds(100,100, 70,70);
14. l1.add("C");
15. l1.add("C++");
16. l1.add("Java");
17. l1.add("PHP");
18. final List l2=new List(4, true);
19. l2.setBounds(100,200, 70,70);
20. l2.add("Turbo C++");
21. l2.add("Spring");
22. l2.add("Hibernate");
23. l2.add("CodeIgniter");
24. f.add(l1); f.add(l2); f.add(label); f.add(b);
25. f.setSize(450,450);
26. f.setLayout(null);
27. f.setVisible(true);
28. b.addActionListener(new ActionListener() {
29. public void actionPerformed(ActionEvent e) {
30. String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex())
;
31. data += ", Framework Selected:";
32. for(String frame:l2.getSelectedItems()){
33. data += frame + " ";
34. }
35. label.setText(data);
36. }
37. });
38. }
39. public static void main(String args[])
40. {
41. new ListExample();
42. }
43. }

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.

AWT Scrollbar class declaration


1. public class Scrollbar extends Component implements Adjustable, Accessible

Java AWT Scrollbar Example


1. import java.awt.*;
2. class ScrollbarExample{
3. ScrollbarExample(){
4. Frame f= new Frame("Scrollbar Example");
5. Scrollbar s=new Scrollbar();
6. s.setBounds(100,100, 50,100);
7. f.add(s);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. new ScrollbarExample();
14. }
15. }

Output:

Java AWT Scrollbar Example with Adjustment Listener


1. import java.awt.*;
2. import java.awt.event.*;
3. class ScrollbarExample{
4. ScrollbarExample(){
5. Frame f= new Frame("Scrollbar Example");
6. final Label label = new Label();
7. label.setAlignment(Label.CENTER);
8. label.setSize(400,100);
9. final Scrollbar s=new Scrollbar();
10. s.setBounds(100,100, 50,100);
11. f.add(s);f.add(label);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. s.addAdjustmentListener(new AdjustmentListener() {
16. public void adjustmentValueChanged(AdjustmentEvent e) {
17. label.setText("Vertical Scrollbar value is:"+ s.getValue());
18. }
19. });
20. }
21. public static void main(String args[]){
22. new ScrollbarExample();
23. }
24. }

Output:

Java AWT Panel


The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.

It doesn't have title bar.

AWT Panel class declaration


1. public class Panel extends Container implements Accessible

Java AWT Panel Example


1. import java.awt.*;
2. public class PanelExample {
3. PanelExample()
4. {
5. Frame f= new Frame("Panel Example");
6. Panel panel=new Panel();
7. panel.setBounds(40,80,200,200);
8. panel.setBackground(Color.gray);
9. Button b1=new Button("Button 1");
10. b1.setBounds(50,100,80,30);
11. b1.setBackground(Color.yellow);
12. Button b2=new Button("Button 2");
13. b2.setBounds(100,100,80,30);
14. b2.setBackground(Color.green);
15. panel.add(b1); panel.add(b2);
16. f.add(panel);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String args[])
22. {
23. new PanelExample();
24. }
25. }

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.

1. public abstract void actionPerformed(ActionEvent e);

Java ActionListener Example: On Button click


1. import java.awt.*;
2. import java.awt.event.*;
3. public class ActionListenerExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("ActionListener Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(ActionEvent e){
13. tf.setText("Welcome to Javatpoint.");
14. }
15. });
16. f.add(b);f.add(tf);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }

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.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }

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.

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListe
ner{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }

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.

1. public abstract void itemStateChanged(ItemEvent e);

Java ItemListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class ItemListenerExample implements ItemListener{
4. Checkbox checkBox1,checkBox2;
5. Label label;
6. ItemListenerExample(){
7. Frame f= new Frame("CheckBox Example");
8. label = new Label();
9. label.setAlignment(Label.CENTER);
10. label.setSize(400,100);
11. checkBox1 = new Checkbox("C++");
12. checkBox1.setBounds(100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. checkBox2.setBounds(100,150, 50,50);
15. f.add(checkBox1); f.add(checkBox2); f.add(label);
16. checkBox1.addItemListener(this);
17. checkBox2.addItemListener(this);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if(e.getSource()==checkBox1)
24. label.setText("C++ Checkbox: "
25. + (e.getStateChange()==1?"checked":"unchecked"));
26. if(e.getSource()==checkBox2)
27. label.setText("Java Checkbox: "
28. + (e.getStateChange()==1?"checked":"unchecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
34. }

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.

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

1. public abstract void keyPressed(KeyEvent e);


2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);

Java KeyListener Example


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,100,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. l.setText("Key Pressed");
21. }
22. public void keyReleased(KeyEvent e) {
23. l.setText("Key Released");
24. }
25. public void keyTyped(KeyEvent e) {
26. l.setText("Key Typed");
27. }
28.
29. public static void main(String[] args) {
30. new KeyListenerExample();
31. }
32. }

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.

Methods of WindowListener interface


The signature of 7 methods found in WindowListener interface are given below:

1. public abstract void windowActivated(WindowEvent e);


2. public abstract void windowClosed(WindowEvent e);
3. public abstract void windowClosing(WindowEvent e);
4. public abstract void windowDeactivated(WindowEvent e);
5. public abstract void windowDeiconified(WindowEvent e);
6. public abstract void windowIconified(WindowEvent e);
7. public abstract void windowOpened(WindowEvent e);

Java WindowListener Example


1. import java.awt.*;
2. import java.awt.event.WindowEvent;
3. import java.awt.event.WindowListener;
4. public class WindowExample extends Frame implements WindowListener{
5. WindowExample(){
6. addWindowListener(this);
7.
8. setSize(400,400);
9. setLayout(null);
10. setVisible(true);
11. }
12.
13. public static void main(String[] args) {
14. new WindowExample();
15. }
16. public void windowActivated(WindowEvent arg0) {
17. System.out.println("activated");
18. }
19. public void windowClosed(WindowEvent arg0) {
20. System.out.println("closed");
21. }
22. public void windowClosing(WindowEvent arg0) {
23. System.out.println("closing");
24. dispose();
25. }
26. public void windowDeactivated(WindowEvent arg0) {
27. System.out.println("deactivated");
28. }
29. public void windowDeiconified(WindowEvent arg0) {
30. System.out.println("deiconified");
31. }
32. public void windowIconified(WindowEvent arg0) {
33. System.out.println("iconified");
34. }
35. public void windowOpened(WindowEvent arg0) {
36. System.out.println("opened");
37. }
38. }

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. public static final int NORTH

2. public static final int SOUTH

3. public static final int EAST

4. public static final int WEST

5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the


components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Example of BorderLayout class:

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.

Constructors of GridLayout class

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.

Example of GridLayout class


1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.

Fields of FlowLayout class

1. public static final int LEFT

2. public static final int RIGHT

3. public static final int CENTER

4. public static final int LEADING

5. public static final int TRAILING

Constructors of FlowLayout class

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.

Example of FlowLayout class


1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. }
26. }

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:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class

1. public static final int X_AXIS

2. public static final int Y_AXIS

3. public static final int LINE_AXIS

4. public static final int PAGE_AXIS

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the


components with the given axis.

Example of BoxLayout class with Y-AXIS:


1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
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.Y_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample1 b=new BoxLayoutExample1();
22. }
23. }

Example of BoxLayout class with X-AXIS

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.

Constructors of CardLayout class

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.

Commonly used methods of CardLayout class

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.

Example of CardLayout class

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.

AWT Canvas class Declaration


1. public class Canvas extends Component implements Accessible

Java AWT Canvas Example


1. import java.awt.*;
2. public class CanvasExample
3. {
4. public CanvasExample()
5. {
6. Frame f= new Frame("Canvas Example");
7. f.add(new MyCanvas());
8. f.setLayout(null);
9. f.setSize(400, 400);
10. f.setVisible(true);
11. }
12. public static void main(String args[])
13. {
14. new CanvasExample();
15. }
16. }
17. class MyCanvas extends Canvas
18. {
19. public MyCanvas() {
20. setBackground (Color.GRAY);
21. setSize(300, 200);
22. }
23. public void paint(Graphics g)
24. {
25. g.setColor(Color.red);
26. g.fillOval(75, 75, 150, 75);
27. }
28. }
Output:

You might also like