Monkeys at Keyboards: The Javanomicon
© Michael James Heron
Topic: Java Programming
Level: 2
Version: delta

Nationalism is an infantile disease. It is the measles of mankind
Albert Einstein

4 - Event Driven Programming 1

PreviousTable of ContentsNext
Forum


Chapter Objectives

By the end of this chapter, the reader will be able to:

  • Be able to optimise simple programs for maintainability.
  • Be able to develop simple event-driven applets.
  • Be able to make use of buttons in their applets.
  • Be able to make use of scroll-bars in their applets.


4.1

Introduction

In the past three chapters we haven't actually covered much new territory as far as Java goes. This chapter is where the book starts for real as we spend some time delving into the event driven programming structure of the Java programming language.

Event driven programming is a development paradigm that seeks to model computer functionality in response to the actions of the user. The Java programming language has very powerful event driven support built into the fundamental framework, and in the short term we are going to be using applets to explore this functionality.

This chapter is concerned primarily with explaining how Java deals with events and how the user can create graphical user interfaces within Java code. In the process we will discuss two of the components Java provides for building interfaces: the button and the scrollbar. In the next chapter we will spend some time looking at the various other tools Java provides for making exciting GUI displays.

4.2

Swing and AWT

There are two families of GUI components provided by the Java language. These are the AWT (Abstract Windows Toolkit) library and the Swing library.

AWT is the older of the families, and was the original method for implementing user interfaces in Java. The intention behind AWT was to allow for a consistent approach to functionality across a number of different platforms. Java is a platform independent language, and it defeats the purpose of providing such a language if the interface to a Java application requires redesigning on different platforms, and so the AWT was provided to Java developers.

The problem with AWT is that while it addresses a very real need for consistent functionality across platforms, the look and feel of AWT applications is different depending on where they are deployed. On a Windows system, they use the Windows components to represent GUI aspects. The same application on a Macintosh will utilise the Macintosh look and feel. An application deployed on a Solaris workstation will use Motif, and so on.

Many developers found this approach unsatisfactory and requested a library of GUI components that not only behaved consistently over numerous platforms, but also had a consistent appearance. This was provided in Java version 1.2 in the form of the Swing GUI architecture.

Although Swing is now a mature and very useable GUI implementation, AWT still has the edge in terms of support - even fairly archaic browsers usually have substantial support for AWT, whereas it requires a slightly more modern browser before Swing components are properly rendered.

Swing on the other hand has a much more flexible and powerful architecture and supports much more complex interfaces. We will be making use of some of this functionality throughout the book.

Comparison of Swing and AWT
Fig 4.1: Comparison of Swing and AWT
Historical note:

The earliest versions of Java do not offer any Swing architecture at all. Versions prior to Java 1.5 have had an entirely different look and feel for Swing applications - this theme was called metal. Newer versions of Java use the Ocean theme, which is the one you'll see in all the screenshots in this book.


Swing and AWT differ primarily in how they implement their interfaces. AWT is a heavyweight component framework... this means that the majority of the work is handled by the operating system itself. This is the reason that the look and feel of an application differs depending on the system on which it is deployed. The operating system deals with how they look, how they behave, and how they interface with the Java Runtime Environment.

Swing on the other hand is a lightweight component framework- most of the work is dealt with by the Swing components themselves. The operating system has relatively little involvement in their look or behaviour. All the code for drawing the components and handling their behaviour is provided by the Java Runtime Environment.

Most of this is done transparently - there is little need for you to understand what is actually going on when a component is drawn. For this book we will be using the Swing GUI architecture, mainly because of its increased power and improved consistency. Functionally the code needed to implement an interface in AWT is almost identical to the code needed to implement an interface in Swing, so if you can code using one set of components it is not a difficult task to migrate to another.

4.3

The Event Driven Programming Structure

In order to understand what we mean by event driven programming we must first understand what we mean by an event.

Simply put, an event is a notification to Java that something has happened. Java supports a large number of different kinds of events for different kind of components, and almost all of them are triggered in response to user actions.

For example, a user clicks on a button - this triggers an event. A user types something into a text component - this triggers an event. The user clicks on a scrollbar - this also triggers an event. Java provides events for dealing with most conceivable ways of interacting with a user interface, not simply the most obvious.

Each GUI component in Java can trigger a number of events. Some events are common to all components - for example, all components can trigger events when the mouse pointer is hovered over them. However, Java has a number of events that are triggered only by specific components. We will be looking at two of these kinds of events in this chapter.

By default, Java doesn't care if an event is triggered - if we wish to register an interest in a particular event, we must indicate to Java where the code to deal with the event is located. We do this by registering a listener object for a particular component. If a component has no listener object registered, then Java assumes we are uninterested in the events triggered by the component.

Listener objects listen for particular kinds of events - registering a particular kind of listener object for a component indicates we are interested only in listening for those specific kinds of events. We'll talk more about this in a few moments when we talk about buttons in Swing.

When an event is triggered on a component that has a registered listener object, Java checks to see what kind of event has been triggered. If we've registered an interest in when a button has been pressed, and an event is triggered because the mouse pointer was moved over the component, then Java does nothing. If however we have registered an interest in an event and that particular kind of event is triggered, Java then calls a method associated with that event on the registered listener object.

Technically we break Java event-related objects down into two categories (which are not mutually exclusive). We have event dispatchers and event handlers.

Event dispatchers are those that generate events at appropriate points in the execution of a Java program. They maintain a list of all interested listener objects, and when an event occurs they are responsible for ensuring that all registered listener objects are notified and that the appropriate contextual information is passed onwards.

Event handlers are those objects that actually handle the event-specific code that should be executed whenever an event occurs. These are each of the individual listener objects.

Throughout this text, we look only at writing event handlers. Most of what we require from event dispatchers is already handled by the provided Java libraries.

This whole idea is easier to show in practice than it is to explain, so we'll look at a first event driven applet using a button.

4.4

Buttons in Swing

All GUI components in Java are built from objects. We'll talk about this some more in a later chapter. For now, all we're going to look at is how to use them, not how the objects themselves work.

Remember our Hello World applet? In chapter one and two we looked at some of the things it's possible to do within the paint method of this applet. In this chapter we look at the init method and how we use it to develop a GUI for our Java applets.

The first thing we need to do in order to make use of a GUI component is to create a variable that is going to hold it. We declare variables in Java by giving the type of the variable and a name by which we refer to it - we do exactly the same thing when creating an object.

The scope of a GUI component in an applet is important - in the vast majority of cases, all your components are going to have class wide scope (remember the idea of scope? See the second chapterif you don't). You will often need to refer to these variables in many different methods when developing an event driven Java applet, and so we will pre-empt this requirement by ensuring that all of our components have class wide scope.

The type of a variable that holds a button component in Swing is called a JButton. However, Java won't know by default what a JButton is - we need to include the following line at the top of our JApplet:

import javax.swing.*; 

We use this JButton in the same way we use int, float or boolean to create a variable:

JButton myButton; 

We're going to build our applet incrementally, using the structure of the Hello World applet we looked at in chapter one. The only difference to start with is that we will remove the g.drawstring line from the paint method - this applet is not about displaying a string on the screen, it is about placing a button:

import java.awt.*; 
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;


public class MyFirstApplet extends JApplet {

public void init() {
}


public void paint (Graphics g) {
super.paint (g);
}

}

This is the start point we'll be using for all our applets from this point onwards. It is a skeleton applet that does nothing except give us a framework for working within.

The first thing we're going to do is create a variable for holding our button, using the line of code we saw above. As mentioned before, we are going to make this a class wide variable and thus it must be declared at the top of the class outside of any of the methods:

import java.awt.*; 
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;


public class MyFirstApplet extends JApplet {
/*
We add the class wide variable that will hold our button at the top of the class ,
within the first set of braces but outside of any method.
*/

JButton myButton;
public void init() {
}


public void paint (Graphics g) {
super.paint (g);
}

}

That's a start! A voyage of a thousand miles begins with a single step, and we've just taken ours. Do you feel proud of yourself? You should... it's a start, and once you have a start, the rest is inevitable.

Now we've got a variable that we can use as a container for our button... but we need to put something into it. You see, we haven't actually created a button at this point - all we've created is a variable that's going to hold one somewhere along the line. The distinction here is quite subtle and will be explored in a later chapter of the book.

Setting up the variable is the first part of what we must do. Next we must put something into it. We do this within the init method of our applet. All our components get declared as class wide variables, but we configure them within the init method.

The next thing we must do is put an actual button into our variable. We do this using the new keyword - we know the syntax of this from chapter two, but we'll have to wait until chapter five before we discuss what it means. The line of code we need looks like this:

myButton = new JButton ("Press Me!"); 

This code creates an actual button object and puts it into the variable we created. The button we created has the text 'Press Me!' across it - by changing the text between the brackets, we can put whatever we want across the button. We can even use HTML, which we'll talk about later in this chapter.

This code goes into the init method:


public void init() {
myButton = new JButton ("Press Me!");
}

Okay, we're doing well... we've created a variable, and we've put an actual button into it. The next thing we have to do is draw it on the screen. Before we actually tell Java to draw the component, it exists only in the computer's memory - you can run this applet and no button will be seen.

The applet in which we are developing our interface has a method associated with it, and this method is called add. The add method is used to draw a component onto the applet. The add method takes two parameters. One is the component to be drawn, and the second where to draw it.

By default, Java applets use what is called a layout manager to determine where components are placed. Layout managers deal with all the awkward parts of setting up an interface - for example, where do components get drawn if an applet is resized?

By default, Swing applets use a layout manager called BorderLayout - this layout manager breaks the applet into five separate regions:

BorderLayout manager regions
Fig 4.2: BorderLayout manager regions

We must tell Java into which of these regions we want to place our component. The line of code to add our button to the center of the applet is:

add (myButton, BorderLayout.CENTER); 

We will look at how to switch off this layout manager in a few moments - although they are useful when developing formal user interfaces, they do little but complicate the issue at this stage of our development. For now, just trust in me the same way you trust in the inexorable pull of gravity.

Adding this line of code into our applet makes the init method look like this:


public void init() {
myButton = new JButton ("Press Me!");
add (myButton, BorderLayout.CENTER);
}

With these lines of code, we are ready to compile and execute our applet to see our button in all its glory:

MyFirstApplet Screenshot
Fig 4.3: MyFirstApplet Screenshot

So now we have an applet that contains a button. You can press the button, and it'll behave exactly like you expect a button to behave, except it won't actually do anything. It'll flash when you click it and generally look responsive, but try as you might, it'll do nothing else.

Every time we click the button, we trigger an event. In the case of a button being clicked, it triggers what is called an action event. Alas, we haven't told Java that we're interested in listening for these events, and so Java simply ignores them. In order for our applet to actually do something, we need to register our interest.

This is slightly more complex than putting the button on the screen, since we must simultaneously register interest and provide the code for dealing with the events.

Registering our interest in an event is easy... our button has a method called addActionListener that tells Java we want to have some code executed whenever an action event is triggered.

As a parameter to this method we must pass information on where the code for dealing with this event may be found. We simply pass in the magic word this which indicates to Java that the code will be found in our applet:


public void init() {
myButton = new JButton ("Press Me!");
add (myButton, BorderLayout.CENTER);
myButton.addActionListener (this);
}

Assimilation of Concepts:

A JButton is an example of an event dispatcher. It does not handle any actual functionality itself - all it does is maintain a list of interested listeners. This is done through the addActionListener method.


Compile the applet again and it won't work. It'll spit out an error - the reason it gives an error is that we've told Java that our applet contains the code for dealing with an action event, but it contains nothing of the sort. Only applets that have a special keyword in their class definition can be registered as listener objects - in the case of our button, our class definition must be expanded as follows:

import java.awt.*; 
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;

/*
We need to add these two words to our class definition...
they indicate to Java that our class has all the methods required to perform the
task of listening for action events.
*/

public class MyFirstApplet extends JApplet implements ActionListener
{
JButton myButton;

public void init() {
myButton = new JButton ("Press Me!");
add (myButton, BorderLayout.CENTER);
myButton.addActionListener (this);
}


public void paint (Graphics g) {
super.paint (g);
}

}

The specifics of this don't matter. What we are saying to Java is that our current class will be listening for Action events, and so Java should trust us when we register it as a listener object with addActionListener.

So we compile this, and Java spits out another error. Once again, Java has been betrayed, because we have no method within our applet that is suitable for dealing with action events. We must add a new method to our applet.

Whenever Java catches an action event, it executes a method called actionPerformed on the appropriate listener object. Our applet does not contain any method with this name, and so Java refuses to allow us to register it as a listener object. We must include this method in our applet. It doesn't need to actually do anything, it just needs to be there:

import java.awt.*; 
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;


public class MyFirstApplet extends JApplet implements ActionListener {
JButton myButton;

public void init() {
myButton = new JButton ("Press Me!");
add (myButton, BorderLayout.CENTER);
myButton.addActionListener (this);
}


public void paint (Graphics g) {
super.paint (g);
}

/*
We need to add this method to our applet - any code that should be executed when an
action event is triggered should go into this method. This method takes a parameter
of type ActionEvent. We’ll talk about this next chapter.
*/

public void actionPerformed (ActionEvent e) {
}

}

Compiling this applet will once again work - but still when we press the button, nothing happens. We have registered our interest in action events, we have added the implements ActionListener keywords to the class definition, and we've added the actionPerformed method to our applet, and yet still nothing happens.

We have however implemented the framework we need, and now any code that we wish to be executed when the button is pressed can be placed into the actionPerformed method. We're going to start off quite slowly at the moment and simply have the applet print out some text to the console whenever we press the button. We do this using System.out.println:


public void actionPerformed (ActionEvent e) {
System.out.println ("The button was just pressed!");
}

Assimilation of Concepts:

The actionPerformed method in our JApplet is the event handler - the event dispatcher (the button) maintains a list of interested listener objects (in this case, the applet), and then when it is pressed it executes the handler method (actionPerformed) in each of these listener objects.


Now every time the button is pressed, the text 'The button was just pressed!' is printed out to the console. Congratulations, you've just written your first event driven applet!

4.5

Null Layout

The BorderLayout manager is quite cumbersome. For one thing, it only allows you to use five components on an applet. It doesn't let us choose exactly where to put things, it only gives us some rough regions in which we can place components. If we place components in the center, as with our button, it draws them in ludicrous proportions.

Using layout managers properly is far too complex to discuss at this point in the book, so we are going to cop out and simply switch them off entirely. We can do this with the following line of code placed in the init method:

setLayout (null); 

This tells Java that we don't want to use any of its predefined managers... instead we will choose where components go, thanks very much. Since we are no longer using the BorderLayout manager, we must change any add method calls we use. We simply remove the mention of the BorderLayout and pass only a single parameter - the component to add. For example, we could rewrite our init method in our just completed applet like so:


public void init() {
setLayout (null);
myButton = new JButton ("Press Me!");
add (myButton);
myButton.addActionListener (this);
}

We can compile the applet, and it'll work just fine - but when we execute it, there's no button on the screen. This is because Java has gone all huffy and decided that if you don't tell it exactly where it should put the components, then it's not going to bother putting them anywhere.

Each component in Java has a method called setBounds that can be used to indicate where they should be drawn on the screen. The setBounds method takes four integer parameters. The first parameter is the x co-ordinate where to begin drawing, the second is the y co-ordinate. The third is a length parameter and the fourth is a height parameter. Remember these parameters? They're exactly the same ones we used to draw rectangles and ovals in chapter one.

In conjunction, these four parameters draw what is called a bounding rectangle on the applet. For example, on our myButton variable:

myButton.setBounds (10, 20, 100, 50); 

X is 10, Y is 20, the length is 100 and the height is 50. This creates the following bounding rectangle:

Bounding rectangle
Fig 4.4: Bounding rectangle

Components are drawn as best they can be within the specified bounding rectangle. The rectangle itself isn't drawn on the screen, it is merely used as a guide by Java. If your bounding rectangle is too small for the component, Java will only draw a partial section of the component within the rectangle - it won't automatically resize the bounds.

Java tip

Using null layout is a temporary measure until we can actually do the topic of layout managers some justice. Don't get used to it!


Switching off the layout manager means that your applet will no longer properly redraw itself when resized or maximised - we'll look at how to solve that problem in a later chapter.

Switching off the layout manager and setting the bounds on our component leaves us with the final version of this applet - the basic framework we have explored here is the same for all event driven applications, even if the names of the events and components change. With this in mind, it is possible to use the code for this applet as a building block for later applet development. All of the basic ideas are explored here - all we have to do is develop our knowledge a little further to expand our capabilities.

import java.awt.*; 
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;


public class MyFirstJApplet extends JAppletimplements ActionListener {
JButton myButton;

public void init() {
myButton = new JButton ("Press Me!");
setLayout (null);
add (myButton);
myButton.addActionListener (this);
myButton.setBounds (10, 10, 100, 50);
}


public void paint (Graphics g) {
super.paint (g);
}


public void actionPerformed (ActionEvent e) {
System.out.println ("The button was just"pressed!");
}

}

Run this applet

Click here to see the applet ScrollbarExample working.


4.6

Scrollbars

Next in this chapter we are going to look at a second type of component and a second type of event.

The scrollbar control is another one of the components in the Swing library - it is often of limited use except as a vehicle for exploring events. Most components that could conceivably use a scrollbar as part of their execution need to be set up somewhat differently than through the use of isolated scrollbars. We'll see one of these in the next chapter.

The name of the Scrollbar component within Swing is JScrollBar. As with the button, we must create a variable that will hold this scrollbar. The basic structure for setting up a component remains constant regardless of the component itself:

  1. Declare a variable that holds the component
  2. Put something into the variable using the new keyword.
  3. Add the component to the applet
  4. If interested, register a listener object.

So for step one, we use the following line of code:

JScrollbar myScrollbar; 

As with the button variable, this should be declared at the top of the class as a variable with class wide scope.

Within the init method of our applet, we perform steps two and three:


public void init() {
setLayout (null);
// Step One
myScrollbar = new JScrollBar();
// Step Two
add (myScrollBar);
myScrollbar.setBounds (10, 10, 100, 20);
}

As you can see, the code for this is very similar to the code for setting up a JButton. The difference is in how this component triggers events.

A scrollbar doesn't trigger action events. Action events indicate when a definite action has been taken - for example, pressing a button. Scrollbars don't have a definite action associated with them, but their values can be adjusted. Scrollbars trigger an adjustment event when they are changed.

We register a listener object for adjustment events in the same way as we register a listener object for action events - the only difference is we use the addAdjustmentListener method instead of addActionListener:


public void init() {
setLayout (null);
myScrollbar = new JScrollBar();
add (myScrollBar);
myScrollbar.setBounds (10, 10, 100, 20);
myScrollbar.addAdjustmentListener (this);
}

Since we are interested in adjustment events and not action events, we must also change the implements section of the class definition so that we are acting as an AdjustmentListener rather than an ActionListener:


public class MyScrollbarExample extends JApplet implements AdjustmentListener {

We're almost there... just a little bit more to go.

When Java recognises that an adjustment event has been triggered and it finds an interested listener object, it calls the method adjustmentValueChanged on the listener object - this is the adjustment event equivalent of actionPerformed:


public void adjustmentValueChanged (AdjustmentEvent e) {
}

We place our code into this method in the same way we place code into actionPerformed - any time the event is triggered (for example, the scrollbar is adjusted) the method adjustmentValueChanged is called.

Our complete scrollbar applet looks like this:

import java.awt.*; 
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;


public class MyScrollbarExample extends JApplet implementsAdjustmentListener {
JScrollBar myScrollbar;

public void init() {
setLayout (null);
myScrollbar = new JScrollBar();
add (myScrollbar);
myScrollbar.addActionListener (this);
myScrollbar.setBounds (10, 10, 100, 50);
}


public void paint (Graphics g) {
super.paint (g);
}


public void adjustmentValueChanged (AdjustmentEvent e) {
System.out.println ("The scrollbar was just " +"adjusted!");
}

}

Run this applet

Click here to see the applet ScrollbarExample working.


4.7

Scrollbar Configuration

Scrollbars set up in this way are only partially configured - we need to be able to specify some more details in order to make them useful. For one thing, we use the same JScrollBar component for both horizontal and vertical scrollbars, so we need to be able to indicate which of these we wish to use.

We can do this by making use of one of the overloaded constructor methods for the JScrollBar:

JScrollBar myScroll = new JScrollBar (JScrollBar.HORIZONTAL); 
JScrollBar myScroll = new JScrollBar (JScrollBar.VERTICAL);

We also need to be able to specify what range of values the scrollbar can be used for - we use the setMinimum and setMaximum methods for this:

myScroll.setMinimum (1); 
myScroll.setMaximum (100);

And also we need to be able to change what value the JScrollBar currently has:

myScroll.setValue (50); 

We can use an equivalent method, getValue to get what value the scrollbar is currently pointing to. For example, we could change our handler method above to take this into account:


public void adjustmentValueChanged (AdjustmentEvent e) {
System.out.println ("The scrollbar was just adjusted to value " + myScroll.getValue
());
}

Run this applet

Click here to see the applet ScrollbarExample2 working.


Java tip

The JScrollBar control will most likely not be configured to your needs by simply creating it and adding an adjustment listener. It requires a bit more setup through the setMinimum and setMaximum methods.


4.8

Setting the colour of components

We can make use of the Swing architecture to change the colour of the components we draw, making use of two methods:

Colour methods
Fig 4.5: Colour methods

import java.awt.*; 
import javax.swing.*;


public class ColouredComponents extends JApplet {
JButton myButton;
JScrollBar myScroll;

public void init() {
setLayout (null);
myButton = new JButton ("Press Me!");
myButton.setForeground (Color.BLUE);
myButton.setBackground (Color.RED);
myButton.setBounds (20, 20, 100, 50);
myScroll = new JScrollBar (JScrollBar.HORIZONTAL);
myScroll.setForeground (Color.YELLOW);
myScroll.setBackground (Color.PINK);
myScroll.setBounds (20, 100, 300, 20);
add (myButton);
add (myScroll);
}

}

By making use of these methods, we can easily create truly hideous interfaces with very little difficulty:

Hideous colouring
Fig 4.6: Hideous colouring

Run this applet

Click here to see the applet ColouredComponents working.


Java tip

Don't use custom colours on components unless you have a genuine need. Most of the time, a consistent interface is better than a garish interface - there are some occasions in which you may want to make use of coloured components. For example, if you are developing a Java front-end to a first-strike nuclear missle system, you might want to make the 'Fire Missiles' button bright red so as to distinguish it and mark it as dangerous (red being the natural colour for danger).


Java tip

If you are going to use custom colours in your programs, then be consistent in your choices. If the 'Fire Missiles' button is red, then so too should all the other dangerous buttons. Similarly, the button for asking for a cup of tea shouldn't be marked bright red (unless the tea is also deadly. Perhaps it is laced with arsenic) - be consistent in your colour choices so that they are a genuine aid to usability.


In most cases, you'll want to maintain the standard look of the Swing components, but where you have a very specific need for colour components, they can be implemented very simply as can be seen above.

4.9

HTML In Swing Components

Many Swing components have a textual component as part of their makeup - like for example, a JButton. There are ways to change the colours, which we've just seen, and there are ways to change the font (which we'll see in the next chapter). However, we can also use HTML codes to allow us to fully configure how the text of a Swing component will appear.

We don't need to know much HTML to be able to make use of this... all we need to know is that our HTML text must begin with the code , and must end with . Between these two tags, we place whatever text we want for our component.

For example, to create a JButton that uses HTML code (but doesn't do anything with it), we could use the following:

myButton = new JButton ("<HTML>Press me!</html>");

Of course, this won't do anything - so we would incorporate other HTML tags to make our button appear the way we want it to. Some of these that you may find useful:

Some HTML codes
Fig 4.7: Some HTML codes

myButton = new JButton ("<html><center><u> Press </u></center><br><center> Me! </center></html>");

This particular HTML will create a button that looks like the following:

An HTML button
Fig 4.8: An HTML button

Run this applet

Click here to see the applet HtmlButton working.


As with changing the background and foreground colour of components, such formatting should be used sparingly - there are several good reasons for using HTML within text components in certain circumstances, but you should at least take some time out and think through the desireability of incorporating it into your projects.

Java tip

HTML on components often looks very garish - limit it to what you have a genuine need for.


4.10

Conclusion

So far we've only covered two types of component and the event driven structure. This is an important first step - all of the rest of our development will be built upon these concepts.

We've only looked at buttons and scrollbars - we haven't yet looked at any of the ways of providing meaningful output to the user. In the next chapter we'll cover some more GUI components and look at the Java method of displaying message boxes for information or confirmation.

4.11

Reader exercises

Exercise one

Create a new JApplet. Add a JButton with the text 'Press Me To Change My Colour' and register it with an ActionListener.

Change the background colour of the JButton to blue.

Provide an actionPerformed method that will change the background colour of the button to red if it is currently blue, and to blue if it is currently red.

Exercise two

Create a new JApplet.

Add a scrollbar that has a vertical orientation and position it at the far right hand side of the applet. Don't implement a listener object for it.

Add a second scrollbar that has a horizontal orientation and position it at the bottom of the screen. Don't implement a listener object for this scrollbar either.

Add a JButton in the middle of the applet. Register a listener object for this.

When the button is pressed, output the current values of each scrollbar to the console.

Exercise three

Create a new JApplet that makes use of buttons and scrollbars and the graphics methods we have already discussed to setup an interface that simulates a simple tape-deck system. It should have a scrollbar for the volume, buttons for each of the tape operations, and a suitable graphic for the tape-deck itself.

Tape Deck
Fig 4.9: Tape Deck

Your interface should be non-functional... it is an exercise in layout, not in functionality.

Exercise four

Place a scrollbar on a JApplet. The scrollbar should allow for values between one and twelve to be set. When the scrollbar is moved, your applet should display the corresponding month to the console. One is January, two is February, and so on.

Further Reading

The following table details further reading on the topic in this chapter, and also any external resources that you may find useful.

ResourceDescription
Example Programs from this chapterThis is a zip file of all the programs shown in this chapter.
Lecture Slides for this chapterThis zip file contains the Powerpoint lecture slides that accompany this chapter.

PreviousTable of ContentsNext

© 2004-2006 Michael James Heron