ActionEvents
Introduction.
Now that we have developed a couple GUIs that don't actually interact with
users you should hopefully be interested in at least some basic ways that
a user can invoke program responses to their actions on a GUI. We
will start with the most basic and then add to these later in the course.
Hopefully, by this time you will have an even greater appreciation for the
alternatives. We start with ActionEvents which are monitored through ActionListeners. The ActionListener interface actually has only one method called actionPerformed( ) which allows the user to determine what action the user took on the GUI for all components that have an associated ActionListener. ActionListeners can be added to a variety of GUI components such as
Since we only have presented JButton and JTextField at this point in the course, these are the only components that we will have programs monitor for user events. In this webpage we will again develop GUIs using both an applet and an application. Our first program is an applet called RepeatTheInput.java. |
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class RepeatTheInput extends JApplet implements ActionListener {
} // end RepeatTheInput class |
This program does the following
The following contains the HTML file. The size affects the appearance significantly. |
<html> <applet code="RepeatTheInput.class" width=450 height=100> </applet> </html> |
When this applet is run you should see the following on your screen. |
Though the text fields will be blank and white.
You should mimic my inputs for your first try. When you are done, click on the Update button to get the following. |
You should now adjust the inputs and again click the
Update button. Notice how the results adjust without restarting the
program. This is one of the advantages of developing these sorts of
forms that contain both the input components and the output components. Now we will modify this applet to turn it into an application. An Application Based GUI. Now I want to run what should seem like almost the same program, but as an application. We will discuss the code after presenting the code and running it. You should call the file RepeatTheInputApp.java. |
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class RepeatTheInputApp extends JFrame implements ActionListener {
} // end RepeatTheInputApp class
} // end class ExitWindow |
The discussion of the code follows. Make sure to focus on the differences between the applet and the application.
Notice how when you compile the RepeatTheInputApp program, you get a class called RepeatTheInputApp.class but you also get a class called ExitWindow.class. When you run the program the form will not look much different than the one for the applet. |
Pressing the update button results in the following. |
This GUI is quite stable, particularly since it accepts string inputs. But you can keep modifying the contents without restarting the program. |