There are four things to know before you begin:
Each Swing GUI program contains one top-level Swing container: JFrame (app), JApplet(applet) or JDialog.
A JFrame implements a window with standard decorations (border, title, ...).
The top-level container (e.g.,JFrame) has a default content panel. Often when you refer to the toplevel container, you are also referring to the default content panel, and vice versa.
You can specify zero or more JPanels that are contained within the content panel. The JPanels are used to organize the GUI into logical sense.
All content panes (the main container in JFrame and Japplet) have default BorderLayout.
All JPanel objects have default FlowLayout.
Each GUI component can be (must be) contained in exactly one container. There is a containment hierarchy that has the top-level container as its root.
To include a component on a GUI: (1) instantiate it, (2) create the event handler for it, (3) add it to the proper container.
Listener | event | ActionListener | click a button | WindowListener | close the main window | MouseListener | click mouse button | MouseMotionListener | move mouse | ListSelectionListener | list selection changes |
---|
or extend a class that implements a listener interface
public class EventClass implements ActionListener { ...
button1.addActionListener(new EventClass());
actionPerformed
code in the ActionListener
public void actionPerformed(ActionEvent e) {
... // do stuff to handle event
}
The Swing timer is the easiest way to implement animation. Like a Javascript interval timer, it fires an event after the interval time has elapse.
Here is the API for the Swing Timer:
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/Timer.html
The methods of greatest importance to us are: start(), stop(), isRunning(), setDelay()
.
The API for the ActionListener interface is here:
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/ActionListener.html
We must implement actionPerformed()
, which is the code that is executed when a timer "goes off."
The Swing Timer is a nifty class that lets us set up timers.
We can start and stop each timer. We can set a delay time for the timer.
When the timer "goes off" the specified "listener" code will be executed.
Warning, there is a Timer class in java.util.Timer
.
We don't want to use that one. We want to use javax.swing.Timer
.