Poornima College of Engineering, Jaipur
Experiment – 01
Advance Java Lab (5CS4-24)
Class – B.Tech III Year, V Sem.
Objective: (a) Write a program in java for event handling using JavaAWT.
Code:
import java.awt.*;
import java.awt.event.*;
public class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,60,180,30);
Button b = new Button("Click Here");
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();
Department of Computer Engineering
Poornima College of Engineering, Jaipur
}
}
Output:
Event Handling in Java
(b) Objective: Write a program in java for implementing Action Listener in Java (on ButtonClick).
import java.awt.*;
import java.awt.event.*;
// Driver Class
public class ActionListenerExample {
// main function
public static void main(String[] args){
// Create a frame
Frame f = new Frame("AWT ActionListener Example");
// Set the size
f.setSize(400, 200);
// Set the layout
Department of Computer Engineering
Poornima College of Engineering, Jaipur
f.setLayout(null);
// Make the frame visible
f.setVisible(true);
// Set the background color of the frame
f.setBackground(Color.LIGHT_GRAY);
// Create a button
Button b = new Button("Click Me");
// Set the positions
b.setBounds(160, 100, 80, 40);
// Add button to the frame
f.add(b);
// Set the background color of the button
b.setBackground(Color.GREEN);
// Create a text field
final TextField tf = new TextField();
// Set the positions
tf.setBounds(50, 50, 300, 30);
// Add text field to the frame
f.add(tf);
// Create a label
Label lb = new Label();
Department of Computer Engineering
Poornima College of Engineering, Jaipur
// Set the positions
lb.setBounds(100, 150, 300, 30);
// Add label to the frame
f.add(lb);
// Add an action listener to the button
b.addActionListener(new ActionListener() {
// Override the actionPerformed() method
public void actionPerformed(ActionEvent e){
// Update the text of the label
lb.setText("Hey " + tf.getText() + "! "
+ "Welcome to Advance Java!");
}
});
}
}
Output;
Department of Computer Engineering