001 /*
002 * Created on Jun 10, 2008
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 *
014 * Copyright @2008-2010 the original author or authors.
015 */
016 package org.fest.swing.driver;
017
018 import static org.fest.swing.driver.JComboBoxEditableQuery.isEditable;
019 import static org.fest.swing.driver.JTableStopCellEditingTask.stopEditing;
020 import static org.fest.util.Collections.list;
021
022 import java.awt.Point;
023
024 import javax.swing.JComboBox;
025 import javax.swing.JTable;
026
027 import org.fest.swing.annotation.RunsInEDT;
028 import org.fest.swing.cell.JTableCellWriter;
029 import org.fest.swing.core.Robot;
030
031 /**
032 * Understands an implementation of <code>{@link JTableCellWriter}</code> that knows how to use
033 * <code>{@link JComboBox}</code>es as cell editors.
034 *
035 * @author Alex Ruiz
036 * @author Yvonne Wang
037 */
038 public class JTableComboBoxEditorCellWriter extends AbstractJTableCellWriter {
039
040 private final JComboBoxDriver driver;
041
042 public JTableComboBoxEditorCellWriter(Robot robot) {
043 super(robot);
044 driver = new JComboBoxDriver(robot);
045 }
046
047 /** {@inheritDoc} */
048 @RunsInEDT
049 public void enterValue(JTable table, int row, int column, String value) {
050 JComboBox editor = doStartCellEditing(table, row, column);
051 selectOrType(editor, value);
052 stopEditing(table, row, column);
053 }
054
055 private void selectOrType(JComboBox editor, String value) {
056 boolean selectValue = !isEditable(editor);
057 if (!selectValue) selectValue = list(driver.contentsOf(editor)).contains(value);
058 if (selectValue) {
059 driver.selectItem(editor, value);
060 return;
061 }
062 driver.enterText(editor, value);
063 }
064
065 /** {@inheritDoc} */
066 @RunsInEDT
067 public void startCellEditing(JTable table, int row, int column) {
068 doStartCellEditing(table, row, column);
069 }
070
071 @RunsInEDT
072 private JComboBox doStartCellEditing(JTable table, int row, int column) {
073 Point cellLocation = cellLocation(table, row, column, location);
074 robot.click(table, cellLocation); // activate JComboBox editor
075 JComboBox comboBox = waitForEditorActivation(table, row, column);
076 cellEditor(cellEditor(table, row, column));
077 return comboBox;
078 }
079
080 @RunsInEDT
081 private JComboBox waitForEditorActivation(JTable table, int row, int column) {
082 return waitForEditorActivation(table, row, column, JComboBox.class);
083 }
084 }