Credits

Saturday, February 19, 2011

More of Java's Event Handling

 Event handling makes a Java GUI program more interactive and with the different event types (e.g ActionEvent for buttons, MouseEvent for mouse actions, KeyEvent for key pressed, ItemEvent for check box or list item), a programmer can have full use of Java to make the program more dynamic.


The program below prompts a user to enter a value for text field and either a text field ENTER key or a button click can produce the label greetings.

[+/-] show/hide


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUIHelloEventQuiz extends JFrame implements ActionListener{
//Container con = getContentPane();
JPanel pane = new JPanel();
JLabel lbl1 = new JLabel("Enter Your Name:");
JTextField tf = new JTextField(15);
JButton btn = new JButton ("Press me!");
JLabel lbl2 = new JLabel(" ");
public GUIHelloEventQuiz(){


pane.add(lbl1);
pane.add(tf);

btn.addActionListener(this);
tf.addActionListener(this);
pane.add(btn);
pane.add(lbl2);
add(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setContentPane(con);
}

public void actionPerformed(ActionEvent e){
//Object x = e.getSource();
lbl2.setText("Hello "+tf.getText());
}

public static void main (String args[]){
GUIHelloEventQuiz quiz = new GUIHelloEventQuiz();
quiz.setTitle("Greetings");
quiz.setSize(300,200);
quiz.setVisible(true);
}
}

AddThis