Tuesday, March 16, 2010

Java Applet's Event Handling

One can use event - handling methods in Java's program the same way we write event - method embedded applications. 

So, apart from creating an Applet parent - child relationship, we create the listener interface so that our components may solicit response for every action we do  including but not limited to action buttons or mouse clicks and window movements.

See the program below for a simple illustration of button and labels in an applet.

[+/-] show/hide

* To change this template, choose Tools | Templates
* and open the template in the editor.

* @author Rose
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class AppletGreetEvent extends Applet implements ActionListener {
JLabel greeting1 = new JLabel("Hello. Who are you?");
JLabel greeting2 = new JLabel();
Font bigFont = new Font("Times New Roman", Font.ITALIC,24);
JButton pressMe = new JButton("Press Me");
JTextField answer = new JTextField(" ",10);

public void init()
answer.requestFocus();// focus for the textfield

public void start()
{ greeting2.setText("This is a sample applet.");}

public void actionPerformed(ActionEvent thisEvent)
String name=answer.getText();

greeting2.setText("Hi "+name);

No comments: