Although the program of Stage D outputs the current date and time whenever the JButton component is clicked, the program sends this output to the standard output, i.e., to the terminal window that runs the program. What we really want to do is to copy the date and time into the JTextField component. And it is the variable tJTextField of the main method of GetDateProg that points to the JTextField object that we want to be updated each time the user clicks on the button.
How can we refer to this JTextField object within the actionPerformed method? We cannot just use tJTextField as this variable is local to the main method, and, anyway, the main method is in a different class from the actionPerformed method.
The easiest way is to alter the constructor for the listener object so that tJTextField is passed as an argument:
JButtonListener tJButtonListener = new JButtonListener(tJTextField);In this way, when the JButtonListener object is being created, the constructor knows which JTextField object we want to be altered: it is the one pointed to by tJTextField.
What can the constructor do with this information? Well, it can make its own copy of the pointer:
public JButtonListener(JTextField pJTextField) { iJTextField = pJTextField; }where iJTextField is a private field of the JButtonListener object.
So when the JButtonListener object is created, it stores a pointer to the JTextField object in a field of the JButtonListener object. Whenever the actionPerformed method is executed, it just has to alter the contents of the object pointed to by iJTextField.
In order to change the value of a JTextField object, we need to apply a method called setText to the object, passing the appropriate string as an argument. Since we actually want to set the textfield to a string describing the current date and time, we need to do:
Date tDate = new Date(); iJTextField.setText("" + tDate);Here is the complete text of this new version of the JButtonListener class:
0088: // // JButtonListener.java 0089: // Stage E: implementing the ActionListener interface. 0090: // Barry Cornelius, 22nd November 1999 0091: import java.awt.event. ActionEvent; 0092: import java.awt.event. ActionListener; 0093: import java.util. Date; 0094: import javax.swing. JTextField; 0095: public class JButtonListener implements ActionListener 0096: { 0097: private JTextField iJTextField; 0098: public JButtonListener(final JTextField pJTextField) 0099: { 0100: iJTextField = pJTextField; 0101: } 0102: public void actionPerformed(final ActionEvent pActionEvent) 0103: { 0104: final Date tDate = new Date(); 0105: iJTextField.setText("" + tDate); 0106: } 0107: } 0108:
The GetDateProg program for this stage is the same as that used for Stage D. An example of what happens when the JButton component is clicked is shown in the Figure.