Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Java Lecture 15-2: Swing I. Handling events in Swing application: theory, e

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko


Bookmark and Share

Handling events

What is event-driven programming? Java Event Handling: event types, registering for events; event objects; listener methods and adapters.

Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All the object has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source.

Every event handler requires three pieces of code:

  1. In the declaration for the event handler class, one line of code specifies that the class either implements a listener interface or extends a class that implements a listener interface. For example:

    Code:

    public class MyClass implements ActionListener {

  2. Another line of code registers an instance of the event handler class as a listener on one or more components. For example:

    Code:

    someComponent.addActionListener(instanceOfMyClass);
  3. In the event handler class, a few lines of code implement the methods in the listener interface. For example:

    Code:

    public void actionPerformed(ActionEvent e) {<br />
         ...//code that reacts to the action...<br />
    }

Event handlers can be instances of any class. Often an event handler that has only a few lines of code is implemented using an anonymous inner class -- an unnamed class defined inside of another class. Anonymous inner classes can be confusing at first, but once you're used to them, they make the code clearer by keeping the implementation of an event handler close to where the event handler is registered.

SwingApplication has two event handlers. One handles window closing (window events); the other handles button clicks (action events). We've already seen the window- closing code. Here is the code that handles button clicks in the SwingApplication:

Code:


button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
      numClicks++;
      label.setText(labelPrefix + numClicks);
   }
});

In general, to detect when the user clicks an on-screen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source), using the addActionListener method. When the user clicks the on-screen button, the button fires an action event. This results in the invocation of the action listener's actionPerformed method (the only method in the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about the event and its source.

Swing components can generate many kinds of events. The following table lists a few examples.

Examples of events and their associated event listeners
Act that results in the event Listener type
User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener
User closes a frame (main window) WindowListener
User presses a mouse button while the cursor is over a component MouseListener
User moves the mouse over a component MouseMotionListener
Component becomes visible ComponentListener
Component gets the keyboard focus FocusListener
Table or list selection changes ListSelectionListener

Adding borders around components

If you take another look at the snapshot of SwingApplication, you'll notice that there is extra space surrounding the JPanel on all four edges.

Here is the code that adds a border to the panel:

Code:
 
pane.setBorder(BorderFactory.createEmptyBorder(
            30, //top
            30, //left
            10, //bottom
            30) //right
  );

This border simply provides some empty space around the panel's contents -- 30 extra pixels on the top, left, and right, and 10 extra pixels on the bottom. Borders are a feature that JPanel inherits from the JComponent class.

Example three: CelsiusConverter

Our next example, CelsiusConverter, does something that's somewhat useful: It is a simple conversion tool. The user enters a temperature in degrees Celsius and clicks the Convert... button, and a label displays the equivalent in degrees Fahrenheit.

Let's examine the code to see how CelsiusConverter parses the number entered in the JTextField. First, here's the code that sets up the JTextField:

Code:

JTextField tempCelsius = null;
...
tempCelsius = new JTextField(5);

The integer argument passed in the JTextField constructor, 5 in the example, indicates the number of columns in the field. This number is used along with metrics provided by the current font to calculate the field's preferred width. This number does not limit how many character the user can enter.

We want to handle the button-click event, so we add an event listener to the button.

Code:


JButton convertTemp;
...
convertTemp.addActionListener(this);
...
public void actionPerformed(ActionEvent event) {
   // Parse degrees Celsius as a double and convert to Fahrenheit.
   int tempFahr=(int)((Double.parseDouble(
                              tempCelsius.getText())) * 1.8 + 32);
   fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}

The getText method is called on the text field, tempCelsius, to retrieve the data within it. Next, the parseDouble method parses the text as a double before converting the temperature and casting the result to an integer. Finally, the setText method is called on the fahrenheitLabel to display the converted temperature. All this code is found in the event handler for the button, as the conversion happens only once the button is clicked.

You can make a JButton be the default button. At most one button in a top-level container can be the default button. The default button typically has a highlighted appearance and acts clicked whenever the top-level container has the keyboard focus and the user presses the Return or Enter key. The exact implementation depends on the look and feel. You set the default button by invoking the setDefaultButton method on a top-level container's root pane:

//In the constructor for a JDialog subclass:

Code:

getRootPane().setDefaultButton(setButton);

Adding HTML

You can use HTML to specify the text on some Swing components, such as buttons and labels. We can spice up the CelsiusConverter program by adding HTML text to the fahrenheitLabel and adding an image to the convertTemp button. The revised program is CelsiusConverter2.


First, let's look at how we specify the HTML tags for the fahrenheitLabel. As you can see from this code, the temperature (tempFahr) is displayed one of three different colours, depending on how hot or cold the converted temperature is:

Code:


// Set fahrenheitLabel to new value and font colour based
// on temperature.
if (tempFahr <= 32) {
   fahrenheitLabel.setText("<html><font color=blue>"
                              + tempFahr
                  + "° Fahrenheit </font></html>");
} else if (tempFahr <= 80) {
   fahrenheitLabel.setText("<html><font color=green>"
                              + tempFahr
                  + "° Fahrenheit </font></html>");
} else {
   fahrenheitLabel.setText("<html><font color=red>"
                              + tempFahr
                  + "° Fahrenheit </font></html>");
}

To add HTML code to the label, simply put the ¡HTML¿ tag at the beginning of a string, and then use any valid HTML code in the remainder of the string. Using HTML can be useful for varying the text font or colour within a button and for adding line breaks. To display the degree symbol, we use the HTML code &#176.

If the string is to be all one size and colour, you don't have to use HTML. You can call the setFont method to specify the font of any component.

Adding an icon

Some Swing components can be decorated with an icon -- a fixed-size image. A Swing icon is an object that adheres to the Icon interface. Swing provides a particularly useful implementation of the Icon interface: ImageIcon. ImageIcon paints an icon from a GIF or a JPEG image. Here's the code that adds the arrow graphic to the convertTemp button:

Code:

ImageIcon icon = new ImageIcon("images/convert.gif",
                     "Convert temperature");
...
convertTemp = new JButton(icon);

The first argument of the ImageIcon constructor specifies the file to load, relative to the directory containing the application's class file. The second argument provides a description of the icon that assistive technologies can use.


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy