Skip to content

Commit 94b0ca2

Browse files
committed
SwingObjectWidget: set values by string comparison
Previously, we were trying to set the JComboBox value with a new instance of the object. We don't always have the possibility to keep a list of the allowed choices for the current model, nor can we override the `equals()` method for the `Object`s of this widget instance. So we have to fall back to comparing all combobox items to the current value by their `toString()` and `ObjectService.getName()` strings.
1 parent 93e963b commit 94b0ca2

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

src/main/java/org/scijava/ui/swing/widget/SwingObjectWidget.java

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,23 @@ public boolean supports(final WidgetModel model) {
108108
@Override
109109
public void doRefresh() {
110110
final Object value = get().getValue();
111-
if (value == comboBox.getSelectedItem()) return; // no change
112-
comboBox.setSelectedItem(value);
111+
if (comboBox.getSelectedItem().toString().equals(nameOf(value))) return; // no change
112+
updateComboBox(comboBox, value);
113+
}
114+
115+
private void updateComboBox(final JComboBox<Object> comboBox, final Object value) {
116+
for (int i = 0; i < comboBox.getModel().getSize(); i++)
117+
{
118+
if (comboBox.getItemAt(i).toString().equals(nameOf(value)))
119+
{
120+
comboBox.setSelectedIndex(i);
121+
break;
122+
}
123+
}
124+
}
125+
126+
private String nameOf(final Object value) {
127+
return value == null ? "" : context().service(ObjectService.class).getName(value);
113128
}
114129

115130
private class NamedObjectCellRenderer implements ListCellRenderer<Object> {
@@ -120,7 +135,7 @@ private class NamedObjectCellRenderer implements ListCellRenderer<Object> {
120135
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
121136
boolean cellHasFocus) {
122137
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
123-
renderer.setText(value == null ? "" : context().service(ObjectService.class).getName(value));
138+
renderer.setText(nameOf(value));
124139
renderer.setToolTipText(value == null ? null : value.toString());
125140
return renderer;
126141
}

0 commit comments

Comments
 (0)