[Schmitzm-commits] r2100 - in trunk/schmitzm-core/src: main/java/de/schmitzm/swing test/java/de/schmitzm/testing

scm-commit at wald.intevation.org scm-commit at wald.intevation.org
Fri Oct 5 14:52:41 CEST 2012


Author: mojays
Date: 2012-10-05 14:52:41 +0200 (Fri, 05 Oct 2012)
New Revision: 2100

Added:
   trunk/schmitzm-core/src/main/java/de/schmitzm/swing/EditableComboBox.java
Modified:
   trunk/schmitzm-core/src/test/java/de/schmitzm/testing/SwingUtilTest.java
Log:
New EditableComboBox

Added: trunk/schmitzm-core/src/main/java/de/schmitzm/swing/EditableComboBox.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/swing/EditableComboBox.java	                        (rev 0)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/swing/EditableComboBox.java	2012-10-05 12:52:41 UTC (rev 2100)
@@ -0,0 +1,238 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ * 
+ * This file is part of the SCHMITZM library - a collection of utility 
+ * classes based on Java 1.6, focusing (not only) on Java Swing 
+ * and the Geotools library.
+ * 
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ * 
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ * 
+ * Contributors:
+ *     Martin O. J. Schmitz - initial API and implementation
+ *     Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.swing;
+
+import java.awt.Color;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.util.Vector;
+
+import javax.swing.ComboBoxModel;
+import javax.swing.JComboBox;
+import javax.swing.JTextField;
+import javax.swing.UIManager;
+
+
+/**
+ * {@link JComboBox} which is editable. The input can be edit manually and a
+ * possible fitting list value is automatically completed.<br>
+ * Note: This class can also be used as "normal" combo box, when editable
+ * property is reset to {@code false}.
+ * @author Martin O.J. Schmitz
+ */
+public class EditableComboBox<E> extends JComboBox<E> implements KeyListener, FocusListener {
+
+  /** Flag indicates whether text input is automatically marked on fucus gain. */
+  protected boolean autoSelectOnFocus = true;
+  /** Last value set by {@link #keyReleased(KeyEvent)}. Used to determine if key stroke
+   *  has changed the value. */
+  private String lastValue = null;
+
+  /** Holds the background color explicitly, because we have to change it manually
+   *  when combo box becomes disabled. */
+  private Color enabledBackground;
+  
+  /**
+   * Creates a new combo box.
+   */
+  public EditableComboBox() {
+    super();
+    init();
+  }
+
+  /**
+   * Creates a new combo box.
+   */
+  public EditableComboBox(ComboBoxModel aModel) {
+    super(aModel);
+    init();
+  }
+
+  /**
+   * Creates a new combo box.
+   */
+  public EditableComboBox(E[] items) {
+    super(items);
+    init();
+  }
+
+  /**
+   * Creates a new combo box.
+   */
+  public EditableComboBox(Vector items) {
+    super(items);
+    init();
+  }
+  
+  /**
+   * Initializes the combo box. Called by every constructor. 
+   */
+  protected void init() {
+    this.enabledBackground = getBackground();
+    setEditable(true);
+    
+    getEditor().getEditorComponent().addFocusListener(this);
+    getEditor().getEditorComponent().addKeyListener(this);
+    setSelectedItem(null);
+  }
+  
+  
+  /**
+   * Returns whether the input text is automatically selected on focus gain.
+   */
+  public boolean isAutoSelectOnFocus() {
+    return autoSelectOnFocus;
+  }
+
+  /**
+   * Sets whether the input text is automatically selected on focus gain.
+   */
+  public void setAutoSelectOnFocus(boolean autoSelectOnFocus) {
+    this.autoSelectOnFocus = autoSelectOnFocus;
+  }
+  
+  /**
+   * Enables or disables the combo box.
+   */
+  public void setEnabled(boolean enabled) {
+    super.setEnabled(enabled);
+    // If combo box is editable, the disabled background is white!?
+    // So we have to set the disabled background manually
+    // Note: use super.setBackground(.) so that color is not stored
+    //       in "this.enabledBackground"
+    super.setBackground( enabled ? enabledBackground : UIManager.getColor("TextField.inactiveBackground") );
+  }
+  
+  /**
+   * Sets the background color.
+   */
+  @Override
+  public void setBackground(Color bg) {
+    this.enabledBackground = bg;
+    super.setBackground(bg);
+  }
+
+// Does not work! Causes that disabled background still remains as in enabled mode!
+//  /**
+//   * Returns the background color.
+//   */
+//  @Override
+//  public Color getBackground() {
+//    // If combo box is disabled, the background was set manually
+//    // to grayed, so we have to return the "remembered" color
+//    if ( !isEnabled() )
+//      return this.enabledBackground;
+//    return super.getBackground();
+//  }
+
+  /**
+   * Does nothing.
+   */
+  @Override
+  public void keyTyped(KeyEvent e) {
+  }
+
+  /**
+   * Does nothing.
+   */
+  @Override
+  public void keyPressed(KeyEvent e) {
+  }
+
+  
+  /**
+   * Checks whether the selection items contain an item which matches the currently
+   * typed pattern (case-insensitive!). If there is such an item, the input text is
+   * preset with this item. The "rest" of the item is marked, so it can easily be
+   * overwritten by manual input.
+   */
+  @Override
+  public void keyReleased(KeyEvent e) {
+    if ( !isEditable() )
+      return;
+    if ( e.isActionKey()  || e.getKeyCode() == KeyEvent.VK_BACK_SPACE )
+      return;
+    JTextField textField = (JTextField)getEditor().getEditorComponent();
+    String inputText = textField.getText();
+    if ( inputText.equalsIgnoreCase(lastValue) )
+      return;
+
+    String prefixPattern = inputText != null ? inputText.toString().toLowerCase() : "";
+    // Do nothing if input text is empty
+    if ( prefixPattern.isEmpty() )
+      return;
+    
+//    if ( lastValue != null && lastValue.toLowerCase().startsWith(prefixPattern) ) {
+//      lastValue =  textField.getText();
+//      return;
+//    }
+    
+    // Check all selection items if there is one, which starts with
+    // the pattern (Quick-and-dirty!)
+    for (int i=0; i<getItemCount(); i++) {
+      Object item = getItemAt(i);
+      String itemText = item != null ? item.toString() : "";
+      if (itemText.toLowerCase().startsWith(prefixPattern)) {
+        // Set input text to selection item
+        setSelectedIndex(i);
+        textField.setText(itemText);
+        // Mark "rest"
+        textField.setCaretPosition(itemText.length());
+        textField.moveCaretPosition(prefixPattern.length());
+        break;
+      }
+    }
+    
+    // Remember last value
+    lastValue = textField.getText();
+  }
+
+  
+  /**
+   * Selects all text in input component if auto selection is enabled.
+   * @see #setAutoSelectOnFocus(boolean)
+   */
+  @Override
+  public void focusGained(FocusEvent e) {
+    if ( isAutoSelectOnFocus() && isEditable() )
+      getEditor().selectAll();
+  }
+
+  /**
+   * Does nothing.
+   */
+  @Override
+  public void focusLost(FocusEvent e) {
+  }
+  
+  
+}

Modified: trunk/schmitzm-core/src/test/java/de/schmitzm/testing/SwingUtilTest.java
===================================================================
--- trunk/schmitzm-core/src/test/java/de/schmitzm/testing/SwingUtilTest.java	2012-10-04 20:29:15 UTC (rev 2099)
+++ trunk/schmitzm-core/src/test/java/de/schmitzm/testing/SwingUtilTest.java	2012-10-05 12:52:41 UTC (rev 2100)
@@ -2,13 +2,22 @@
 
 import static org.junit.Assert.*;
 
+import java.awt.BorderLayout;
 import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
 import java.text.DecimalFormat;
+import java.util.Vector;
 
+import javax.swing.AbstractAction;
+import javax.swing.JButton;
+
 import org.junit.Ignore;
 import org.junit.Test;
 
+import de.schmitzm.swing.EditableComboBox;
 import de.schmitzm.swing.ExceptionDialog;
+import de.schmitzm.swing.JPanel;
 import de.schmitzm.swing.SwingUtil;
 import de.schmitzm.swing.input.FileInputOption;
 import de.schmitzm.swing.input.ManualInputOption;
@@ -99,5 +108,42 @@
       format = SwingUtil.createLimitedDecimalFormat(pattern);
       assertEquals(8, format.getMaximumIntegerDigits());
       assertEquals(2, format.getMaximumFractionDigits());
-}
+	}
+	
+	
+	
+	@Test
+	@Ignore
+	public void testFreeComboBox() throws Throwable {
+      if ( !isInteractive() )
+        return;
+      final Vector<String> items = new Vector<String>();
+      items.add("Item1");
+      items.add("Item2");
+      items.add("Item3");
+      items.add("Item4");
+      final EditableComboBox comboBox = new EditableComboBox(items);
+      
+      JPanel panel = new JPanel(new BorderLayout());
+      // Action to add new item
+      AbstractAction action = new AbstractAction("add") {
+        @Override
+        public void actionPerformed(ActionEvent e) {
+          EditableComboBox cb = comboBox;
+          Object itemName = cb.getSelectedItem();
+          if ( !items.contains(itemName) ) {
+            cb.addItem(itemName);
+          }
+              
+        }
+      };
+      JButton button = new JButton(action);
+
+      
+      panel.setPreferredSize(new Dimension(200,100));
+      panel.add(comboBox, BorderLayout.NORTH);
+      panel.add(button, BorderLayout.SOUTH);
+      
+      TestingUtil.testGui(panel,-1);
+	}
 }
\ No newline at end of file



More information about the Schmitzm-commits mailing list