Synchronized JList and JComboBox?

前端 未结 2 1780

In Java Swing, what\'s the best way for a JList and a JComboBox to be synchronized in terms of the data, i.e., to have the same list of items at an

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 03:58

    Your models - the ListModel for the list and the ComboboxModel for the combobox - need to be synchronized.

    In the general case this would mean writing a special implementation of the models, but in your case you have luck: DefaultComboBoxModel in fact implements ListModel, so you simply can use the same model object for both your components.

    JList list = new JList();
    JComboBox comboBox = new JComboBox();
    DefaultComboBoxModel listModel = new DefaultComboBoxModel();
    // add items to listModel...
    list.setModel(listModel);
    comboBox.setModel(listModel);
    

提交回复
热议问题