Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4114352

Choice box returns confused return value when select on non-exist items

XMLWordPrintable

    • sparc
    • solaris_2.6

      Using JDK 1.1.3 and found out below problem regarding of Choice Box.

      Test Case:

      import java.awt.*;

      public class Test extends Frame {
         public Test() {
      super("This is just a test.");

      Choice choice = new Choice();
      choice.select("1");
      System.out.println("Choice select 1 = " + choice.getSelectedIndex());
      choice.addItem("1");
      choice.select("2");
      System.out.println("Choice select 2 = " + choice.getSelectedIndex());
      choice.addItem("2");
      choice.select("3");
      System.out.println("Choice select 3 = " + choice.getSelectedIndex());
      choice.addItem("3");
      choice.select("1");
      System.out.println("Choice now select 1 = "+choice.getSelectedIndex());
      choice.select("2");
      System.out.println("Choice now select 2 = "+choice.getSelectedIndex());
      choice.addItem("exit");
      add(choice);

      resize(300,300);
      show();
          }

          public boolean action(Event e, Object o) {
      if (e.target instanceof Choice) {
      String objString = (String)o;
      if (objString.equals("exit"))
      System.exit(0);
      }
      return true;
          }
          public static void main(String args[]) {
      new Test();
          }
      }

      Problems found:

      This is what will be returned if you compile and run the test application.

      Choice select 1 = -1
      Choice select 2 = 0
      Choice select 3 = 0
      Choice now select 1 = 0
      Choice now select 2 = 1

      Note that, when first time select("1") and then getSelectedIndex(), it returns
      -1 which is great since the Choice donesn't contain "1" at this time. And -1
      could be used to indicate "not-found".

      Then, addItem("1"), select("2") and getSelectedIndex(). This time, "2" is not
      on the Choice box yet but the getSelectedIndex() returns a 0. Which is the same
      index of "1" on the Choice box.

      This is very confused. You will get a 0 (zero) returned from getSelectedIndex() when you try to select a "non-existing" item. AND you will get a 0 (zero)
      returned from getSelectedIndex() when you try to select the very first item!!

      It would be much better to return a -1 to indicate a "not-found" item.

            dmendenhsunw David Mendenhall (Inactive)
            duke J. Duke
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: