How can the ActionListener interface be used to handle input
How can the ActionListener interface be used to handle input from text fields?
Solution
Please follow the data and description :
ActionListener interface :
It is basically an interface for the class which processes the ActionEvent should particularly implement this interface for the code to execute flawlessly. Now that the object of that respective class must be registered with a component or as a reference. Thus making the object that can be registered using the addActionListener() method. Now when the action event occurs, then that the object\'s actionPerformed method is invoked to perform the action. ActionListener is the interface for many GUI components.
Whenever we create GUI components that will trigger events, we must register them with the event handler. We have a general method called actionPerformed that catches ActionListener events. Similarly we have general method called itemStateChanged that catches ItemListener events.
Now moving on to the Text Fields and ActionListener such that when it is hit the text field is read.
We add implements ActionListener to the line where we define the class. We then need to register the text field as that it is having an event attached to it. This could be done by calling the method addActionListener() on the GUI component. This method requires one argument, a reference to the applet, so we\'ll use keyword this. So, to register the text field userTextField with the action listener, we add the line of code userTextField.addActionListener(this);.
Finally, we need to write code to handle the event. This is done within the method actionPerformed(). For a text field, we want to know what text was typed in. We can access this through the JTextField accessor getText().
CODE :
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
public class ActionTextRelation extends JApplet implements ActionListener
{
private JLabel userLabel;
private JTextField userTextField;
private String message;
@Override
public void init() // set up GUI
{
setLayout(new FlowLayout());
message = \"\"; // initially, draw nothing
userLabel = new JLabel(\"Enter your Data :\"); // create GUI for entering the data
add(userLabel);
userTextField = new JTextField(10);
userTextField.addActionListener(this); // register name field w/ event handler
add(userTextField);
}
@Override
public void paint(Graphics g) // display message string
{
super.paint(g);
g.drawString(message, 10, 50); // print out entered data
}
public void actionPerformed(ActionEvent e) // process \"Enter\" in userTextField
{
message = \"The data entered was: \" + userTextField.getText();
repaint();
}
}
Hope this is helpful.

