List boxes

Bruce Eckel's Thinking in Java Contents | Prev | Next

//: List1.java
// Using lists with action()
import java.awt.*;
import java.applet.*;
 
public class List1 extends Applet {
  String[] flavors = { "Chocolate", "Strawberry",
    "Vanilla Fudge Swirl", "Mint Chip", 
    "Mocha Almond Fudge", "Rum Raisin", 
    "Praline Cream", "Mud Pie" };
  // Show 6 items, allow multiple selection:
  List lst = new List(6, true);
  TextArea t = new TextArea(flavors.length, 30);
  Button b = new Button("test");
  int count = 0;
  public void init() {
    t.setEditable(false);
    for(int i = 0; i < 4; i++)
      lst.addItem(flavors[count++]);
    add(t);
    add(lst);
    add(b);
  }
  public boolean action (Event evt, Object arg) {
    if(evt.target.equals(lst)) {
      t.setText("");
      String[] items = lst.getSelectedItems();
      for(int i = 0; i < items.length; i++)
        t.appendText(items[i] + "\n");
    }
    else if(evt.target.equals(b)) {
      if(count < flavors.length)
        lst.addItem(flavors[count++], 0);
    }
    else 
      return super.action(evt, arg);
    return true;
  }
} ///:~ 

When you press the button it adds items to the top of the list (because of the second argument 0 to addItem( )). Adding elements to a List is more reasonable than the Choice box because users expect to scroll a list box (for one thing, it has a built-in scroll bar) but they don’t expect to have to figure out how to get a drop-down list to scroll, as in the previous example.

However, the only way for action( ) to be called is through a double-click. If you need to monitor other activities that the user is doing on your List (in particular, single clicks) you must take an alternative approach.

handleEvent( )

What if these other methods – action( ) in particular – don’t satisfy your needs? In the case of List, for example, what if you want to catch single mouse clicks but action( ) responds to only double clicks? The solution is to override handleEvent( ) for your applet, which after all is derived from Applet and can therefore override any non- final methods. When you override handleEvent( ) for the applet you’re getting all the applet events before they are routed, so you cannot just assume “This has to do with my button so I can assume it’s been pressed,” since that’s true only for action( ). Inside handleEvent( ) it’s possible that the button has the focus and someone is typing to it. Whether it makes sense or not, those are events that you can detect and act upon in handleEvent( ).

//: List2.java
// Using lists with handleEvent()
import java.awt.*;
import java.applet.*;
 
public class List2 extends Applet {
  String[] flavors = { "Chocolate", "Strawberry",
    "Vanilla Fudge Swirl", "Mint Chip", 
    "Mocha Almond Fudge", "Rum Raisin", 
    "Praline Cream", "Mud Pie" };
  // Show 6 items, allow multiple selection:
  List lst = new List(6, true);
  TextArea t = new TextArea(flavors.length, 30);
  Button b = new Button("test");
  int count = 0;
  public void init() {
    t.setEditable(false);
    for(int i = 0; i < 4; i++)
      lst.addItem(flavors[count++]);
    add(t);
    add(lst);
    add(b);
  }
  public boolean handleEvent(Event evt) {
    if(evt.id == Event.LIST_SELECT ||
       evt.id == Event.LIST_DESELECT) {
      if(evt.target.equals(lst)) {
        t.setText("");
        String[] items = lst.getSelectedItems();
        for(int i = 0; i < items.length; i++)
          t.appendText(items[i] + "\n");
      }
      else 
        return super.handleEvent(evt);
    } 
    else 
      return super.handleEvent(evt);
    return true;
  }
  public boolean action(Event evt, Object arg) {
    if(evt.target.equals(b)) {
      if(count < flavors.length)
        lst.addItem(flavors[count++], 0);
    }
    else 
      return super.action(evt, arg);
    return true;
  }
} ///:~ 

The example is the same as before except for the addition of handleEvent( ). Inside, a check is made to see whether a list selection or deselection has occurred. Now remember, handleEvent( ) is being overridden for the applet, so this occurrence could be anywhere on the form and it could be happening to another list. Thus, you must also check to see what the target is. (Although in this case there’s only one list on the applet so we could have made the assumption that all list events must be about that list. This is bad practice since it’s going to be a problem as soon as another list is added.) If the list matches the one we’re interested in, the same code as before will do the trick.

Note that the form for handleEvent( ) is similar to action( ): if you deal with a particular event you return true, but if you’re not interested in any of the other events via handleEvent( ) you must return super.handleEvent(evt). This is vital because if you don’t do this, none of the other event-handling code will get called. For example, try commenting out the return super.handleEvent(evt) in the code above. You’ll discover that action( ) never gets called, certainly not what you want. For both action( ) and handleEvent( ) it’s important to follow the format above and always return the base-class version of the method when you do not handle the event yourself (in which case you should return true). (Fortunately, these kinds of bug-prone details are relegated to Java 1.0. The new design in Java 1.1 that you will see later in the chapter eliminates these kinds of issues.)



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: February 12, 2015 The evolution of systems engineering with the SysML modeling language has resulted in improved requirements specification, better architectural definition, and better hand-off to downstream engineering. Agile methods have proven successful in the software domain, but how can these methods be applied to systems engineering? Check out this webcast and join Bruce Powel Douglass, author of Real-Time Agility, as he discusses how agile methods have had a tremendous …

  • Companies undertaking an IT project need to find the right balance between cost and functionality. It's important to start by determining whether to build a solution from scratch, buy an out-of-the-box solution, or a combination of both. In reality, most projects will require some system tailoring to meet business requirements. Decision-makers must understand how much software development is enough and craft a detailed implementation plan to ensure the project's success. This white paper examines the different …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date