Credits

Monday, March 7, 2011

Java Applet's Event Handling

 Integrating events in our GUI - oriented program works the same for embedding events on applet and its components.

With the appropriate components and their respective events, we include the necessary event handlers  or methods telling Java how it should respond.

The following are common events normally done in a GUI Java program:

button clicks
text field focus
check box selection
list selection
window movements
mouse movements
keyboard keys

So, it is quite important that we determine the needed action to be performed when we have component events. We next include the necessary interface and add a listener to our component. The button in the sample program below requires and event, thus, we write our codes as follows:


:
i:mport java.awt.event.*;

public class AppletSeatWork extends JApplet implements ActionListener{
JLabel name = new JLabel("Name: ");
JLabel course=new JLabel("Course: ");
JLabel rate=new JLabel ("Rate per unit:");
JLabel units=new JLabel ("Units Enrolled:");
JLabel tuition = new JLabel("Tuition Due:");

JButton compute =new JButton("Calculate");
:
:
public void init( ){
 :
:

compute.addActionListener(this);
add(compute);
:
:} 

With the event methods or event handlers, we specify the needed actions.  The block of event method for button below illustrates the needed action to compute and display result in a text field.

 public void actionPerformed(ActionEvent e)


{


double total = Double.parseDouble(trate.getText())*Double.parseDouble(tunits.getText());


ttuition.setText(""+total);


}

To see the complete program, simply click on read more link. So, apart from including the event package, writing the interface and event methods, we simply provide our applet codes, and events shall be written and performed just like any typical Java program.


[+/-] show/hide



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

public class AppletSeatWork extends JApplet implements ActionListener{
JLabel name = new JLabel("Name: ");
JLabel course=new JLabel("Course: ");
JLabel rate=new JLabel ("Rate per unit:");
JLabel units=new JLabel ("Units Enrolled:");
JLabel tuition = new JLabel("Tuition Due:");

JButton compute =new JButton("Calculate");
JTextField tname = new JTextField(15);
JTextField tcourse = new JTextField(15);
JTextField trate = new JTextField(15);
JTextField tunits = new JTextField(15);
JTextField ttuition = new JTextField(15);
FlowLayout flow = new FlowLayout();

public void init()
{setLayout(flow);
add(name);
add(tname);
add(course);
add(tcourse);
add(rate);
add(trate);
add(units);
add(tunits);
add(tuition);
ttuition.setEditable(false);
add(ttuition);
compute.addActionListener(this);
add(compute);
}
public void actionPerformed(ActionEvent e)
{
double total = Double.parseDouble(trate.getText())*Double.parseDouble(tunits.getText());
ttuition.setText(""+total);
}
}

AddThis