Components: Applets, Panels, Buttons, etc.

Java 1.1 local version very OLD (but useful if SUN site down) and newer 1.5.0 version

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.
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

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 (is a Container) that you can use directly for simple interfaces (can put other Components or Containers into it).

Example: (figure 1)

Notice button instantiation

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
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

E.G., One has components on top of a Window. If a user input event occurs on an event source object (e.g., user clicks the mouse on the window) the event source notifies all the listener objects that the event has occurred. It

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.

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,

Different techniques
  1. Create a class which specifically implements the entire interface, instantiate it, and have a GUI component add an instance of this Listener which links the component to the interface. This is the most distinct (a class for each) with respect to a MVC architecture
  2. let the Frame/Panel on which the GUI is added implement the appropriate Interfaces, then the GUI component's Listener passes this since it is the interface. IF it does this and does not want to implement all of the methods, it can provide empty methods (empty bodies).
  3. use adapter classes: for each of the event listener interfaces that contains more than one method java.awt.event defines a simple "adaptor" class that provides an empty body for each of the methods of the interface. You can then subclass this adaptor class when you are only interested in one or two of the defined methods (e.g MouseAdaptor, WindowAdapter)
  4. inner classes: event listeners can be implemented with anonymous inner classes (example code above -
      button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ System.out.println ("Button: " + arg) }});
    note that the interface is actually defined in the call!) This creates "anonymous" classes which, when compiled, show up as className$#.class files (i.e. myButton$1.class)
    See Core Java Volume 1, pg.215(224) ... depends on edition - see index
  5. low-level event handling - allows programmer to override event-specific methods like processMouseEvent(), processMouseMotionEvent(). Code calls enableEvents() in its init() to register interest in events of that type. See Core Java Chapter 8 for the list of low-level event classes and handling.

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:
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.

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).

Notice the import java.awt.event.*; This package is needed for the Interfaces and Event classes.
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.

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:
One has a canvas on top of a Window. If the user clicks the mouse on the canvas, the canvas gets the event

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.

Multiple Buttons:

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
implements ActionListener
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
and

Components in Swing are identified with J's in front. For example Button becomes JButton ; the JButton tutorial

Other Button Types

Choice (like menus): generates ItemEvent implements ItemListener (method: itemStateChanged())

the applet

getSource() will return an Object (cast it to a Choice object); the addSelectedItem() method supplies the representation of the current choice as a String.

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()

in Swing

For the radio action (one on at a time), the Checkbox can be grouped. When one is selected, the others turn off.

the applet with both the a group (look up CheckboxGroup in the api for more understanding) and an individual


Swing . components are used lately for components because they are "lightweight" (as opposed to "heavyweight"). Swing buttons

Back to Components:

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.

the applet

OR Here is a Java Developer Tech Tip on Validating Numerical Input in a JTextField

Text Areas: extends TextComponent
Java also allows programmers to use multi-lined text as a field (text area). For text areas you must also specify the number of rows:

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:

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)

Lists: List l = new List (5, true);

Applet provides a scrollbar for list items that exceed the viewing area

the applet

???? compiled but nothing happens... (whether true/false)

why not?
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()

LayoutManager

NOTE: If you are using an environment (such as JBuilder) you should read the documentation to see if your GUIBuilder uses a default layout manager. Most of these use no default rather than Java's default of FlowLayout. Thus, what happens is that when you send me your stuff, and I run it from the command line, your layout looks terrible on my machine...it will only look alright on the platform you are using.
LESSON always use an explicit Layout Manager. (suggest GridBag Layout) if you want your java code to be portable.
    public void init() {
	setLayout(new FlowLayout(FlowLayout.LEFT,20,5));

Some examples:

Foundation Classes listing and tutorials examples of use , and tips on choosing

FlowLayout

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));

the applet

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)

	column major?
1 2
3 4
5 6
the applet

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.
Also note this page about not needing double-buffering in Swing.