package org.fest.swing.driver; import static org.fest.assertions.Assertions.assertThat; import org.fest.swing.annotation.RunsInEDT; import org.fest.swing.cell.JComboBoxCellReader; import static org.fest.swing.edt.GuiActionRunner.execute; import org.fest.swing.edt.GuiQuery; import org.fest.swing.edt.GuiTask; import org.fest.swing.fixture.JComboBoxFixture; import org.fest.swing.test.core.RobotBasedTestCase; import org.fest.swing.test.swing.TestWindow; import static org.fest.util.Arrays.array; import org.junit.Test; import javax.swing.*; import javax.swing.plaf.basic.BasicComboBoxEditor; import javax.swing.plaf.basic.BasicComboBoxRenderer; import java.awt.*; public class Bug254_requireSelection_Test extends RobotBasedTestCase { private JComboBox comboBox; private JComboBoxCellReader cellReader; private JComboBoxFixture fixture; @Override protected void onSetUp() { MyWindow window = MyWindow.createNew(); comboBox = window.comboBox; cellReader = new BasicJComboBoxCellReader(); fixture = new JComboBoxFixture(robot, comboBox); robot.showWindow(window); } @Test public void should_return_text_of_selected_item_in_editable_JComboBox() { makeEditableAndSelectIndex(comboBox, 0); robot.waitForIdle(); assertThat(fixture.requireSelection("first")); // assertThat(JComboBoxSelectionValueQuery.selection(comboBox, cellReader)).isSameAs("first"); } @RunsInEDT private static void makeEditableAndSelectIndex(final JComboBox comboBox, final int index) { execute(new GuiTask() { protected void executeInEDT() { comboBox.setEditable(true); comboBox.setSelectedIndex(index); } }); } private static class MyWindow extends TestWindow { private static final long serialVersionUID = 1L; private JComboBox comboBox; private String renderValue(TestValue testValue) { return testValue == null ? null : testValue.toString().toLowerCase(); } @RunsInEDT static MyWindow createNew() { return execute(new GuiQuery() { protected MyWindow executeInEDT() { return new MyWindow(); } }); } private MyWindow() { super(Bug254_requireSelection_Test.class); comboBox = new JComboBox(array(TestValue.values())); comboBox.setSelectedIndex(-1); addComponents(comboBox); comboBox.setEditable(true); comboBox.setEditor(new BasicComboBoxEditor() { @Override public void setItem(Object anObject) { if (anObject instanceof TestValue) { TestValue testValue = (TestValue) anObject; super.setItem(renderValue(testValue)); } } @Override public Object getItem() { String text = editor.getText(); try { return TestValue.valueOf(text.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } }); comboBox.setRenderer(new BasicComboBoxRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { TestValue testValue = (TestValue) value; return super.getListCellRendererComponent(list, renderValue(testValue), index, isSelected, cellHasFocus); } }); } } private static enum TestValue { FIRST, SECOND, THIRD } }