0

How to bind JComboBox which holds String items to Integer value in bean using JGoodies
I want to display in JComboBox names and bind it to some ID value for that name.

  • Welcome to Stack Overflow! To get a positive response here, please show what you have already tried. Ideally, add a [Minimal, Complete, Tested, Readable example](http://stackoverflow.com/help/mcve). – S.L. Barth is on codidact.com Mar 05 '14 at 13:27

1 Answers1

0

Using a MVP architecture, you will have the Presentation SelectInList one who keeps a List of objects that you want to list: ex:

class MyObject {
    private Integer id;
    private String name;
    ...
    //getters and setters
}

class MyView {
    private MyPresentationModel;
    private JComboBox myComboBox;
    ...
    private void buildComponents {
        myComboBox = BasicComponentFactory.createComboBox(getPresentationModel().getMyObjectsSelectionInList(), new ListCellRenderer() {

            protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

            @Override
            public Component getListCellRendererComponent(JList list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
                JLabel renderer = (JLabel) defaultRenderer
                        .getListCellRendererComponent(list, value, index, isSelected,
                            cellHasFocus);

                renderer.setText(((MyObject) value).getName()); //this is point
                return renderer;
            }
        });
    }
}

class MyPresentationModel extends com.jgoodies.binding.PresentationModel {
    private SelectionInList myObjetcsSelectionInList;
    private List<MyObject> list;
    private MyModel myModel;

    public MyPresentationModel(MyModel myModel) {
        this.myModel = myModel;
        list = //LOAD LIST
    }

    public SelectionInList getPeriodTypeSelectionInList() {
        if (myObjetcsSelectionInList == null) {
            myObjetcsSelectionInList = new SelectionInList(list.toArray(new MyObejct[list.size()]), getModel(MyModel.PROPERTY_MY_OBJECT));
            myObjetcsSelectionInList.setSelectionIndex(0);
        }
        return myObjetcsSelectionInList;
    }
    ...
}

class MyModel {
    static public String PROPERTY_MY_OBJECT = "myObject";
    private MyObject myObject;

    // getters and setters
}
samarone
  • 322
  • 2
  • 4