开发者

Swing ComboBox with the choice of "none of the below"

I have a perfectly normal ArrayList<MyObject> that I need to edit and pick an object from.

In the application window, I have a JComboBox to select the appropriate choice from the list. I'm writing an editor dialog for these objects, which just includes a JList of these objects and editor fields. It's easy enough to do; I'll just have a ListModel implementation of some kind. Stick the ArrayList in, access it through the usual fields. The stuff in the GUI list is 1:1 representation of the stuff in the actual list. Easy.

But the combo box in the main application window is giving me a bit of a headache, because I need a special value. Ideally, the first item in the list should be "(None)", and return a null.

Do I just need to write some sort of weird ComboBoxModel implementation for this, or is there an easier, already implemented way 开发者_C百科to do this? I'd definitely imagine this sort of situation has cropped up before.


Implementing your own ComboBoxModel should be quite easy.

Since this solution creates a new Vector from your ArrayList, changes to yourArrayList after creating Vector won't be visible in your JComboBox. If you need this, then you'll have to implement your own ComboBoxModel (see DefaultComboBoxModel implementation).

You would have to do this anyway, since there is no DefaultComboBoxModel constructor that takes a List.

class SpecialComboBoxModel extends DefaultComboBoxModel {
    public final static String NULL_ELEMENT = "<None>";

    public SpecialComboBoxModel(Vector v) {
        super(v);
    }

    @Override
    public int getSize() {
        return super.getSize() + 1;
    }

    @Override
    public Object getElementAt(int index) {
        if( index == 0) {
            return NULL_ELEMENT;
        }
        return super.getElementAt(index - 1);
    }
}


    ArrayList<String> yourArrayList = new ArrayList<String>();
    yourArrayList.add("Value1");
    yourArrayList.add("Value2");
    Vector<String> v = new Vector<String>(yourArrayList);
    dropdown.setModel(new SpecialComboBoxModel(v));


You might want to use a null-object. For example

public class MyObject {
   public static final MyObject NULL_OBJECT = new MyObject();

   ..
}

and then in your ArrayList just call:

arrayList.add(0, MyObject.NULL_OBJECT);

You null-object should have all of its properties set to null (or to some reasonable defaults), and your toString() method (if you are using it), should return "(none)" if all the fields are null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜