These notes show some javax.swing but are based on java.awt . This is done
since much of the notes
concern the use of Listeners - used with almost any GUI and also because the swing components inherit from java.awt.Component. I am going to give some basic component information so you can get started, then I will come back to Swing.
Panels provide the space in which you can build your Applet or application. You can attach any GUI
Component to a Panel, including other Panels. Some AWT components and Swing components. Applets are Panels specifically designed to use on web browsers.
Specifically, the Applet class provided with Java implements a basic Panel
A nice link for quick "how to's" for Swing is here . Make sure to see the original cartwheel duke
Here is one they forgot in their list - for PAINT in both the AWT and Swing . Some discussion on light and heavy-weight components.
Another useful link is solving common component problems
Example: (figure 1)
The String you specify during the instantiation will appear on the Button when it is
displayed on the screen. The string will also be returned for use as identification when an
event has occurred.
NOTE: There are no x, y coordinates because these are relative to the panel and platform.
Instead we will use Layout Managers. The default is the Flow Layout - fills in objects to
the right until it flows to the next line (more later )
The above button doesn't help unless it does something.
Recall that whenever a user clicks a button, an event happens (as with mouseDown and mouseUp events).
Event Handling
Thus, button action methods can be "caught" by first adding a listener for the component
then (1) providing an Listener Interface or (2) providing an "adapter" for the interface.
Notice button instantiation
The Java event handling model is based on the concept of an "event listener". An object
interested in receiving events is an event listener. An object that generates events (event
source) maintains a list of listeners that are interested in being notified when events occur. java.awt.event API
WHY and WHAT again?
When you create a GUI component (an event source), you usually want to tell it what it should do
when a user "uses" it. In Java, there are Event Listeners who "listen" for certain events.
When you add a component to a GUI that generates an event, you also add a listener for that component. e.g.
Button myButton = new Button();
add(myButton); // to the applet or frame
myButton.addActionListener(this);
so it can "hear" when the event occurs and do the right thing.
For the Listener to know what to do, you must define a class that
implements the particular Interface. By writing the method or methods (all of them) that this Interface specifies,
your Listener is implementing the Interface. Pictorally .
For example, in any introductory Java text (I am assuming any since this is quite significant: in Core Java there is a Table 8-1 in the Event Handling chapter) you can see lists of Components and Events they can generate. SUN site. Then, for various types of events, there are Interfaces that are Listeners which must have classes that implement these Listeners. The Listener Interface expects certain methods to be implemented. Review your text Core Java Table 8-1 for event handling summary.
To define a Java callback,
Also see the Java in a Nutshell, 2nd ed. Feature Demo (links on my web page) 1.1 and 1.0
to see examples of these. Here is one of them running
REPEAT (since it is) an important thing to remember: When the user does something, they cause an Event. An
event is a class like everything else in Java... so some kind of event class is instantiated
(upon this action). So, first, one needs to know about the different events .
In java.awt.event you see the Interfaces(ActionListener, ItemListener, etc) as well as the
different Classes (ActionEvent, ComponentEvent, ItemEvent) that the methods of the
Listeners need as parameters.
Now, these Events are all subclasses of AWTEvent which is in java.awt.
So events will inherit all the methods of AWTEvent, which extends EventObject.
These are much different that the methods of the components themselves (like getLabel(),
etc).
Back to buttons:
The mouse outside of the button (but inside of the panel component) creates a MouseEvent and
thus requires the MouseListener.
See this table from Foundation Classes book, Core Java Chapter 8 Table 8-1 , and the MVC web page at New Java 1.1 Event Info
(taken from a SUN page)
for more on event handling and interfaces...and using the MVC architecture.
The methodology used above was using Inner Classes; here the event listeners are
implemented as anonymous inner classes (i.e., note that the class does not implement
the interface explicitly).
here is the applet running Don't forget to
look at the java console.
An alternative is for the class to implement the Listeners. BUT,
Adapters are not interfaces anymore (they have made no-ops for the
method definitions), so since we do not have multiple inheritance, you
would need to either keep the MouseAdapter an inner class, or
subclass your own:
If you don't believe me, run the code yourself buttonApplet.java
Events: are system messages - a result of physical action by a user (usually).
OLD Java 1.0 Event handling:
The above is describing what "happens" with events - but is described in Java 1.0 talk.
(Keep for reference) What really is going on here now? The revised (1.1,etc) event handling
model is essentially a "callback" model.
Distinguishing between multiple buttons can be done by using the target object passed by
the Event object and comparing it to your button objects:
OR
Components in Swing are identified with J's in front.
For example Button becomes JButton ;
the JButton tutorial
Choice (like menus): generates ItemEvent
implements ItemListener (method: itemStateChanged())
Checkbox Buttons are often used as state buttons. They provide toggle values on and
off (T/F). The state of the button is returned as the Object argument for Checkbox events.
(arg is true if checked, false otherwise)
Both the name and state are available. They can be retrieved using getLabel() and
getState()
the applet with both the a group (look up CheckboxGroup in the api for more understanding) and an individual
Back to Components:
the applet
here (MultiListener) is an example of a textArea with Swing
(related to Java 1.0 ) The above is a good example of how you might have components in
different components (make sense) and you want to have a handle on them (use of self as
parameter)
OR how subclassing buttons can direct actions (when the send button was made, it could
have made an IV to ta1)
???? compiled but nothing happens...
(whether true/false)
why not?
Buttons create ActionEvents and thus require the ActionListener Interface with its methods.
To implement the ActionListener Interface, the button must implement the
actionPerformed() Listener Method.
Notice also that it
does not implement the Listeners since it defines them
anonymously, i.e., it uses an anonymous inner class for
the listener.
One has a canvas on top of a Window. If the user clicks the mouse on the canvas, the
canvas gets the event
else {System.out.println("Non-Button event " ); }
cause I never hit the button (no object, only x,y coordinates)
implements ActionListener
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this); and
in Swing
Swing . components are used lately for components because they are "lightweight" (as opposed to "heavyweight"). Swing buttons
For direct user input of information via the keyboard.
You can choose one of four options:
When the user hits return in a text field, the action generates a text field event. You catch
this event in the actionPerformed method of the ListenerInterface.
OR
Here is a Java Developer Tech Tip on Validating Numerical Input in a JTextField
To access the text currently in a TextArea you can use getText()
TextAreas do not generate any unusual events, but you can use other events to drive access
to the text in the event handler:
kinda embarrassing
"If an application wants to perform some action based on an item in this list being selected or activated, it should implement ItemListener or ActionListener as appropriate and register the new listener to receive events from this list." from API : see below for appropriate...
To access the selected items from a list, use the getSelectedItem() or getSelectedItems() methods.(note not getItemSelectable of ItemEvents...)
For single selected lists, any double-click selection in a list will trigger an event that you catch in the actionPerformed() method (first click chooses item, second click triggers action)
For multiple-select lists you need an external event to trigger your actions. For example a button with:
Scrollbar example - see how it works
(Scrollbars generate AdjustmentEvent ... need an AdjustmentListener implement
method adjustmentValueChanged()
public void init() {
setLayout(new FlowLayout(FlowLayout.LEFT,20,5));
Some examples:
Foundation Classes listing and tutorials examples of use , and tips on choosing
Basic - default for every panel, default placement is center
Components added to a panel follow each other in a list fashion. You position horizontally, you can specify the spaces between each component.
setLayout(new FlowLayout(FlowLayout.LEFT,20,5));
BorderLayout
Border provides 5 areas: North, South, East, West, Center
The center represents everything once the directions are filled
the applet
GridLayout
Rows and Columns (fills across row (i.e. columns) first)
See GridBagLayout and CardLayout , Swing Layout Managers
The use of the class Canvas is handy when doing a lot of graphics
drawing. See my canvas page and
the API page for Canvas. If used with double-buffering see here. column major?
1 2
3 4
5 6
the applet
Also note this page about not needing
double-buffering in Swing.