Java/Swing JFC/ComboBox — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:46, 1 июня 2010

Содержание

Add an item after the first item

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.insertItemAt("item0.5", 1);
  }
}





Add an item to the end of the list

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.addItem("item3");
  }
}





Adding and Removing an Item in a JComboBox Component

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    // Add an item to the start of the list
    cb.insertItemAt("item0", 0);
  }
}





A fancy example of JComboBox with a custom renderer and editor

 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// EditableComboBox.java
//A fancy example of JComboBox with a custom renderer and editor used to
//display a list of JLabel objects that include both text and icons.
//
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ruboBoxEditor;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
public class EditableComboBox extends JPanel {
  private BookEntry books[] = {
      new BookEntry("Ant: The Definitive Guide", "covers/ant.gif"),
      new BookEntry("Database Programming with JDBC and Java",
          "covers/jdbc.gif"),
      new BookEntry("Developing Java Beans", "covers/beans.gif"),
      new BookEntry("Developing JSP Custom Tag Libraries",
          "covers/jsptl.gif"),
      new BookEntry("Java 2D Graphics", "covers/java2d.gif"),
      new BookEntry("Java and XML", "covers/jxml.gif"),
      new BookEntry("Java and XSLT", "covers/jxslt.gif"),
      new BookEntry("Java and SOAP", "covers/jsoap.gif"),
      new BookEntry("Java and XML Data Binding", "covers/jxmldb.gif"),
      new BookEntry("Java Cookbook", "covers/jcook.gif"),
      new BookEntry("Java Cryptography", "covers/jcrypto.gif"),
      new BookEntry("Java Distributed Computing", "covers/jdist.gif"),
      new BookEntry("Java I/O", "covers/javaio.gif"),
      new BookEntry("Java in a Nutshell", "covers/javanut.gif"),
      new BookEntry("Java Management Extensions", "covers/jmx.gif"),
      new BookEntry("Java Message Service", "covers/jms.gif"),
      new BookEntry("Java Network Programming", "covers/jnetp.gif"),
      new BookEntry("Java Performance Tuning", "covers/jperf.gif"),
      new BookEntry("Java RMI", "covers/jrmi.gif"),
      new BookEntry("Java Security", "covers/jsec.gif"),
      new BookEntry("JavaServer Pages", "covers/jsp.gif"),
      new BookEntry("Java Servlet Programming", "covers/servlet.gif"),
      new BookEntry("Java Swing", "covers/swing.gif"),
      new BookEntry("Java Threads", "covers/jthread.gif"),
      new BookEntry("Java Web Services", "covers/jws.gif"),
      new BookEntry("Learning Java", "covers/learnj.gif") };
  Map bookMap = new HashMap();
  public EditableComboBox() {
    // Build a mapping from book titles to their entries
    for (int i = 0; i < books.length; i++) {
      bookMap.put(books[i].getTitle(), books[i]);
    }
    setLayout(new BorderLayout());
    JComboBox bookCombo = new JComboBox(books);
    bookCombo.setEditable(true);
    bookCombo.setEditor(new ComboBoxEditorExample(bookMap, books[0]));
    bookCombo.setMaximumRowCount(4);
    bookCombo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("You chose "
            + ((JComboBox) e.getSource()).getSelectedItem() + "!");
      }
    });
    bookCombo.setActionCommand("Hello");
    add(bookCombo, BorderLayout.CENTER);
  }
  public static void main(String s[]) {
    JFrame frame = new JFrame("Combo Box Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new EditableComboBox());
    frame.pack();
    frame.setVisible(true);
  }
}
class BookEntry {
  private final String title;
  private final String imagePath;
  private ImageIcon image;
  public BookEntry(String title, String imagePath) {
    this.title = title;
    this.imagePath = imagePath;
  }
  public String getTitle() {
    return title;
  }
  public ImageIcon getImage() {
    if (image == null) {
      image = new ImageIcon(imagePath);
    }
    return image;
  }
  // Override standard toString method to give a useful result
  public String toString() {
    return title;
  }
}
class ComboBoxEditorExample implements ComboBoxEditor {
  Map map;
  ImagePanel panel;
  ImageIcon questionIcon;
  public ComboBoxEditorExample(Map m, BookEntry defaultChoice) {
    map = m;
    panel = new ImagePanel(defaultChoice);
    questionIcon = new ImageIcon("question.gif");
  }
  public void setItem(Object anObject) {
    if (anObject != null) {
      panel.setText(anObject.toString());
      BookEntry entry = (BookEntry) map.get(anObject.toString());
      if (entry != null)
        panel.setIcon(entry.getImage());
      else
        panel.setIcon(questionIcon);
    }
  }
  public Component getEditorComponent() {
    return panel;
  }
  public Object getItem() {
    return panel.getText();
  }
  public void selectAll() {
    panel.selectAll();
  }
  public void addActionListener(ActionListener l) {
    panel.addActionListener(l);
  }
  public void removeActionListener(ActionListener l) {
    panel.removeActionListener(l);
  }
  //  We create our own inner class to handle setting and
  //  repainting the image and the text.
  class ImagePanel extends JPanel {
    JLabel imageIconLabel;
    JTextField textField;
    public ImagePanel(BookEntry initialEntry) {
      setLayout(new BorderLayout());
      imageIconLabel = new JLabel(initialEntry.getImage());
      imageIconLabel.setBorder(new BevelBorder(BevelBorder.RAISED));
      textField = new JTextField(initialEntry.getTitle());
      textField.setColumns(45);
      textField.setBorder(new BevelBorder(BevelBorder.LOWERED));
      add(imageIconLabel, BorderLayout.WEST);
      add(textField, BorderLayout.EAST);
    }
    public void setText(String s) {
      textField.setText(s);
    }
    public String getText() {
      return (textField.getText());
    }
    public void setIcon(Icon i) {
      imageIconLabel.setIcon(i);
      repaint();
    }
    public void selectAll() {
      textField.selectAll();
    }
    public void addActionListener(ActionListener l) {
      textField.addActionListener(l);
    }
    public void removeActionListener(ActionListener l) {
      textField.removeActionListener(l);
    }
  }
}





ArrayListComboBoxModel Demo

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.AbstractListModel;
import javax.swing.ruboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ArrayListComboBoxModel extends AbstractListModel implements
    ComboBoxModel {
  private Object selectedItem;
  private ArrayList anArrayList;
  public ArrayListComboBoxModel(ArrayList arrayList) {
    anArrayList = arrayList;
  }
  public Object getSelectedItem() {
    return selectedItem;
  }
  public void setSelectedItem(Object newValue) {
    selectedItem = newValue;
  }
  public int getSize() {
    return anArrayList.size();
  }
  public Object getElementAt(int i) {
    return anArrayList.get(i);
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("ArrayListComboBoxModel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Collection col = System.getProperties().values();
    ArrayList arrayList = new ArrayList(col);
    ArrayListComboBoxModel model = new ArrayListComboBoxModel(arrayList);
    JComboBox comboBox = new JComboBox(model);
    Container contentPane = frame.getContentPane();
    contentPane.add(comboBox, BorderLayout.NORTH);
    frame.setSize(300, 225);
    frame.setVisible(true);
  }
}





Color ComboBox: ComboBoxEditor Demo

 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ruboBoxEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.event.EventListenerList;
public class ColorComboBox {
  static class ColorCellRenderer implements ListCellRenderer {
    protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
    // width doesn"t matter as combobox will size
    private final static Dimension preferredSize = new Dimension(0, 20);
    public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
      JLabel renderer = (JLabel) defaultRenderer
          .getListCellRendererComponent(list, value, index,
              isSelected, cellHasFocus);
      if (value instanceof Color) {
        renderer.setBackground((Color) value);
      }
      renderer.setPreferredSize(preferredSize);
      return renderer;
    }
  }
  public static void main(String args[]) {
    Color colors[] = { Color.black, Color.blue, Color.cyan, Color.darkGray,
        Color.gray, Color.green, Color.lightGray, Color.magenta,
        Color.orange, Color.pink, Color.red, Color.white, Color.yellow };
    JFrame frame = new JFrame("Color JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    final JComboBox comboBox = new JComboBox(colors);
    comboBox.setMaximumRowCount(5);
    comboBox.setEditable(true);
    comboBox.setRenderer(new ColorCellRenderer());
    Color color = (Color) comboBox.getSelectedItem();
    ComboBoxEditor editor = new ColorComboBoxEditor(color);
    comboBox.setEditor(editor);
    contentPane.add(comboBox, BorderLayout.NORTH);
    final JLabel label = new JLabel();
    label.setOpaque(true);
    label.setBackground((Color) comboBox.getSelectedItem());
    contentPane.add(label, BorderLayout.CENTER);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Color selectedColor = (Color) comboBox.getSelectedItem();
        label.setBackground(selectedColor);
      }
    };
    comboBox.addActionListener(actionListener);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
class ColorComboBoxEditor implements ComboBoxEditor {
  final protected JButton editor;
  transient protected EventListenerList listenerList = new EventListenerList();
  public ColorComboBoxEditor(Color initialColor) {
    editor = new JButton("");
    editor.setBackground(initialColor);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Color currentBackground = editor.getBackground();
        Color color = JColorChooser.showDialog(editor, "Color Chooser",
            currentBackground);
        if ((color != null) && (currentBackground != color)) {
          editor.setBackground(color);
          fireActionEvent(color);
        }
      }
    };
    editor.addActionListener(actionListener);
  }
  public void addActionListener(ActionListener l) {
    listenerList.add(ActionListener.class, l);
  }
  public Component getEditorComponent() {
    return editor;
  }
  public Object getItem() {
    return editor.getBackground();
  }
  public void removeActionListener(ActionListener l) {
    listenerList.remove(ActionListener.class, l);
  }
  public void selectAll() {
    // ignore
  }
  public void setItem(Object newValue) {
    if (newValue instanceof Color) {
      Color color = (Color) newValue;
      editor.setBackground(color);
    } else {
      // Try to decode
      try {
        Color color = Color.decode(newValue.toString());
        editor.setBackground(color);
      } catch (NumberFormatException e) {
        // ignore - value unchanged
      }
    }
  }
  protected void fireActionEvent(Color color) {
    Object listeners[] = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == ActionListener.class) {
        ActionEvent actionEvent = new ActionEvent(editor,
            ActionEvent.ACTION_PERFORMED, color.toString());
        ((ActionListener) listeners[i + 1])
            .actionPerformed(actionEvent);
      }
    }
  }
}





Color combobox renderer

 
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.ToolTipManager;
import javax.swing.border.rupoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
public class ColorComboRenderer extends JPanel implements ListCellRenderer {
  protected Color m_c = Color.black;
  public ColorComboRenderer() {
    super();
    setBorder(new CompoundBorder(
        new MatteBorder(2, 10, 2, 10, Color.white), new LineBorder(
            Color.black)));
  }
  public Component getListCellRendererComponent(JList list, Object obj,
      int row, boolean sel, boolean hasFocus) {
    if (obj instanceof Color)
      m_c = (Color) obj;
    return this;
  }
  public void paint(Graphics g) {
    setBackground(m_c);
    super.paint(g);
  }
  public static void main(String[] a) {
    JComboBox cbColor = new JComboBox();
    int[] values = new int[] { 0, 128, 192, 255 };
    for (int r = 0; r < values.length; r++)
      for (int g = 0; g < values.length; g++)
        for (int b = 0; b < values.length; b++) {
          Color c = new Color(values[r], values[g], values[b]);
          cbColor.addItem(c);
        }
    cbColor.setRenderer(new ColorComboRenderer());
    
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    f.getContentPane().add(cbColor);
    f.pack();
    f.setSize(new Dimension(300, 80));
    f.show();    
    
  }
}





Combobox combines a button or editable field and a drop-down list.

 
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
public class ComboBox extends JDialog implements ActionListener, ItemListener {
  final String[] authors = { "A", "B", "C", "D", "E", "F" };
  final String[] images = { "a.jpg", "b.jpg", "c.jpg", "d.jpg","e.jpg", "f.jpg" };
  JLabel display = new JLabel();
  JComboBox combobox = new JComboBox(authors);
  JButton button = new JButton("Close");
  ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource("a.jpg"));
  public ComboBox() {
    setLayout(new FlowLayout());
    add(display);
    combobox.setSelectedIndex(-1);
    combobox.addItemListener(this);
    add(combobox);
    
    button.addActionListener(this);
    add(button);
    setSize(300, 300);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
  }
  public static void main(String[] args) {
    new ComboBox();
  }
  public void actionPerformed(ActionEvent e) {
    System.exit(0);
  }
  public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
      JComboBox combo = (JComboBox) e.getSource();
      int index = combo.getSelectedIndex();
      display.setIcon(new ImageIcon(ClassLoader.getSystemResource(images[index])));
    }
  }
}





ComboBox Demo

 
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
 * ComboBoxDemo.java is a 1.4 application that uses these additional files:
 *   images/Bird.gif
 *   images/Cat.gif
 *   images/Dog.gif
 *   images/Rabbit.gif
 *   images/Pig.gif
 */
public class ComboBoxDemo extends JPanel
                          implements ActionListener {
    JLabel picture;
    public ComboBoxDemo() {
        super(new BorderLayout());
        String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
        //Create the combo box, select the item at index 4.
        //Indices start at 0, so 4 specifies the pig.
        JComboBox petList = new JComboBox(petStrings);
        petList.setSelectedIndex(4);
        petList.addActionListener(this);
        //Set up the picture.
        picture = new JLabel();
        picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
        picture.setHorizontalAlignment(JLabel.CENTER);
        updateLabel(petStrings[petList.getSelectedIndex()]);
        picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
        //The preferred size is hard-coded to be the width of the
        //widest image and the height of the tallest image + the border.
        //A real program would compute this.
        picture.setPreferredSize(new Dimension(177, 122+10));
        //Lay out the demo.
        add(petList, BorderLayout.PAGE_START);
        add(picture, BorderLayout.PAGE_END);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }
    /** Listens to the combo box. */
    public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox)e.getSource();
        String petName = (String)cb.getSelectedItem();
        updateLabel(petName);
    }
    protected void updateLabel(String name) {
        ImageIcon icon = createImageIcon("images/" + name + ".gif");
        picture.setIcon(icon);
        picture.setToolTipText("A drawing of a " + name.toLowerCase());
        if (icon != null) {
            picture.setText(null);
        } else {
            picture.setText("Image not found");
        }
    }
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ComboBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn"t find file: " + path);
            return null;
        }
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("ComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new ComboBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application"s GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}





ComboBox Demo 2

 
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/* ComboBoxDemo2.java is a 1.4 application that requires no other files. */
public class ComboBoxDemo2 extends JPanel implements ActionListener {
  static JFrame frame;
  JLabel result;
  String currentPattern;
  public ComboBoxDemo2() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    String[] patternExamples = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
        "yyyy.MM.dd G "at" hh:mm:ss z", "EEE, MMM d, ""yy", "h:mm a",
        "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa" };
    currentPattern = patternExamples[0];
    //Set up the UI for selecting a pattern.
    JLabel patternLabel1 = new JLabel("Enter the pattern string or");
    JLabel patternLabel2 = new JLabel("select one from the list:");
    JComboBox patternList = new JComboBox(patternExamples);
    patternList.setEditable(true);
    patternList.addActionListener(this);
    //Create the UI for displaying result.
    JLabel resultLabel = new JLabel("Current Date/Time", JLabel.LEADING); //==
    // LEFT
    result = new JLabel(" ");
    result.setForeground(Color.black);
    result.setBorder(BorderFactory.createCompoundBorder(BorderFactory
        .createLineBorder(Color.black), BorderFactory
        .createEmptyBorder(5, 5, 5, 5)));
    //Lay out everything.
    JPanel patternPanel = new JPanel();
    patternPanel
        .setLayout(new BoxLayout(patternPanel, BoxLayout.PAGE_AXIS));
    patternPanel.add(patternLabel1);
    patternPanel.add(patternLabel2);
    patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
    patternPanel.add(patternList);
    JPanel resultPanel = new JPanel(new GridLayout(0, 1));
    resultPanel.add(resultLabel);
    resultPanel.add(result);
    patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    add(patternPanel);
    add(Box.createRigidArea(new Dimension(0, 10)));
    add(resultPanel);
    setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    reformat();
  } //constructor
  public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    String newSelection = (String) cb.getSelectedItem();
    currentPattern = newSelection;
    reformat();
  }
  /** Formats and displays today"s date. */
  public void reformat() {
    Date today = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(currentPattern);
    try {
      String dateString = formatter.format(today);
      result.setForeground(Color.black);
      result.setText(dateString);
    } catch (IllegalArgumentException iae) {
      result.setForeground(Color.red);
      result.setText("Error: " + iae.getMessage());
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ComboBoxDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ComboBoxDemo2();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





ComboBox Sample

 
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ComboBoxSample {
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I", "J" };
    String title = (args.length == 0 ? "Example JComboBox" : args[0]);
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentpane = frame.getContentPane();
    JComboBox comboBox1 = new JComboBox(labels);
    comboBox1.setMaximumRowCount(5);
    contentpane.add(comboBox1, BorderLayout.NORTH);
    JComboBox comboBox2 = new JComboBox(labels);
    comboBox2.setEditable(true);
    contentpane.add(comboBox2, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





ComoboBox loads and saves items automatically from a file

 
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ruboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class MemComboBoxDemo extends JFrame {
  protected MemComboBox urlComboBox = new MemComboBox();
  public MemComboBoxDemo() {
    super();
    setSize(300, 100);
    getContentPane().setLayout(new BorderLayout());
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    p.add(new JLabel("Address"));
    urlComboBox.load("addresses.dat");
    ComboBoxListener lst = new ComboBoxListener();
    urlComboBox.addActionListener(lst);
    MemComboAgent agent = new MemComboAgent(urlComboBox);
    p.add(urlComboBox);
    getContentPane().add(p, BorderLayout.NORTH);
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        urlComboBox.save("addresses.dat");
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    setVisible(true);
    urlComboBox.grabFocus();
  }
  class ComboBoxListener implements ActionListener{
    public void actionPerformed(ActionEvent evt) {
      System.out.println( urlComboBox.getSelectedItem());
    }
  }
  public static void main(String argv[]) {
    new MemComboBoxDemo();
  }
}
class MemComboAgent extends KeyAdapter {
  protected JComboBox comboBox;
  protected JTextField editor;
  public MemComboAgent(JComboBox c) {
    comboBox = c;
    editor = (JTextField) c.getEditor().getEditorComponent();
    editor.addKeyListener(this);
  }
  public void keyReleased(KeyEvent e) {
    char ch = e.getKeyChar();
    if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch))
      return;
    int pos = editor.getCaretPosition();
    String str = editor.getText();
    if (str.length() == 0)
      return;
    for (int k = 0; k < comboBox.getItemCount(); k++) {
      String item = comboBox.getItemAt(k).toString();
      if (item.startsWith(str)) {
        editor.setText(item);
        editor.setCaretPosition(item.length());
        editor.moveCaretPosition(pos);
        break;
      }
    }
  }
}
class MemComboBox extends JComboBox {
  public static final int MAX_MEM_LEN = 30;
  public MemComboBox() {
    super();
    setEditable(true);
  }
  public void add(String item) {
    removeItem(item);
    insertItemAt(item, 0);
    setSelectedItem(item);
    if (getItemCount() > MAX_MEM_LEN)
      removeItemAt(getItemCount() - 1);
  }
  public void load(String fName) {
    try {
      if (getItemCount() > 0)
        removeAllItems();
      File f = new File(fName);
      if (!f.exists())
        return;
      FileInputStream fStream = new FileInputStream(f);
      ObjectInput stream = new ObjectInputStream(fStream);
      Object obj = stream.readObject();
      if (obj instanceof ComboBoxModel)
        setModel((ComboBoxModel) obj);
      stream.close();
      fStream.close();
    } catch (Exception e) {
      System.err.println("Serialization error: " + e.toString());
    }
  }
  public void save(String fName) {
    try {
      FileOutputStream fStream = new FileOutputStream(fName);
      ObjectOutput stream = new ObjectOutputStream(fStream);
      stream.writeObject(getModel());
      stream.flush();
      stream.close();
      fStream.close();
    } catch (Exception e) {
      System.err.println("Serialization error: " + e.toString());
    }
  }
}





Create a simple combobox

 
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ComboBox extends JFrame {
  public ComboBox() {
    super("ComboBox");
    getContentPane().setLayout(new BorderLayout());
    Vector cars = new Vector();
    cars.addElement("1");
    cars.addElement("2");
    cars.addElement("3");
    getContentPane().add(new JComboBox(cars));
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    // setResizable(false);
    pack();
    setVisible(true);
  }
  public static void main(String argv[]) {
    new ComboBox();
  }
}





Creating a read-only and editable JComboBox Component

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a read-only combobox
    String[] items = { "item1", "item2" };
    JComboBox readOnlyCB = new JComboBox(items);
    // Create an editable combobox
    items = new String[] { "item1", "item2" };
    JComboBox editableCB = new JComboBox(items);
    editableCB.setEditable(true);
  }
}





Custom ComboBox with Image

 
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
/*
 * CustomComboBoxDemo.java is a 1.4 application that uses the following files:
 *   images/Bird.gif
 *   images/Cat.gif
 *   images/Dog.gif
 *   images/Rabbit.gif
 *   images/Pig.gif
 */
public class CustomComboBoxDemo extends JPanel {
    ImageIcon[] images;
    String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
    /*
     * Despite its use of EmptyBorder, this panel makes a fine content
     * pane because the empty border just increases the panel"s size
     * and is "painted" on top of the panel"s normal background.  In
     * other words, the JPanel fills its entire background if it"s
     * opaque (which it is by default); adding a border doesn"t change
     * that.
     */
    public CustomComboBoxDemo() {
        super(new BorderLayout());
        //Load the pet images and create an array of indexes.
        images = new ImageIcon[petStrings.length];
        Integer[] intArray = new Integer[petStrings.length];
        for (int i = 0; i < petStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon("images/" + petStrings[i] + ".gif");
            if (images[i] != null) {
                images[i].setDescription(petStrings[i]);
            }
        }
        //Create the combo box.
        JComboBox petList = new JComboBox(intArray);
        ComboBoxRenderer renderer= new ComboBoxRenderer();
        renderer.setPreferredSize(new Dimension(200, 130));
        petList.setRenderer(renderer);
        petList.setMaximumRowCount(3);
        //Lay out the demo.
        add(petList, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CustomComboBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn"t find file: " + path);
                return null;
        }
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("CustomComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new CustomComboBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application"s GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {
        private Font uhOhFont;
        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }
        /*
         * This method finds the image and text corresponding
         * to the selected value and returns the label, set up
         * to display the text and image.
         */
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            //Get the selected index. (The index param isn"t
            //always valid, so just use the value.)
            int selectedIndex = ((Integer)value).intValue();
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            //Set the icon and text.  If icon was null, say so.
            ImageIcon icon = images[selectedIndex];
            String pet = petStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(pet);
                setFont(list.getFont());
            } else {
                setUhOhText(pet + " (no image available)",
                            list.getFont());
            }
            return this;
        }
        //Set the font and text when no image was found.
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}





Determining If the Menu of a JComboBox Component Is Visible

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    // Determine if the menu is visible
    boolean isVisible = cb.isPopupVisible();
  }
}





Determining When the Menu of a JComboBox Component Is Displayed

 
import javax.swing.JComboBox;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.setEditable(true);
    MyPopupMenuListener actionListener = new MyPopupMenuListener();
    cb.addPopupMenuListener(actionListener);
  }
}
class MyPopupMenuListener implements PopupMenuListener {
  public void popupMenuWillBecomeVisible(PopupMenuEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
  }
  public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
  }
  public void popupMenuCanceled(PopupMenuEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
  }
}





Displaying the Menu in a JComboBox Component Using a Keystroke

 
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "A", "B", "B", "C", "C" };
    JComboBox cb = new JComboBox(items);
    // Create and register the key listener
    cb.addKeyListener(new MyKeyListener());
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
    // Get pressed character
    char ch = evt.getKeyChar();
    // If not a printable character, return
    if (ch != KeyEvent.CHAR_UNDEFINED) {
      cb.showPopup();
    }
  }
}





Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique

 
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "A", "B", "B", "C" };
    JComboBox cb = new JComboBox(items);
    // Create and register the key listener
    cb.addKeyListener(new MyKeyListener());
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
    int curIx = cb.getSelectedIndex();
    char ch = evt.getKeyChar();
    JComboBox.KeySelectionManager ksm = cb.getKeySelectionManager();
    if (ksm != null) {
      // Determine if another item has the same prefix
      int ix = ksm.selectionForKey(ch, cb.getModel());
      boolean noMatch = ix < 0;
      boolean uniqueItem = ix == curIx;
      // Display menu if no matching items or the if the selection is not unique
      if (noMatch || !uniqueItem) {
        cb.showPopup();
      }
    }
  }
}





Editable ComboBox

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class EditComboBox {
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I", "J" };
    JFrame frame = new JFrame("Editable JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    final JComboBox comboBox = new JComboBox(labels);
    comboBox.setMaximumRowCount(5);
    comboBox.setEditable(true);
    contentPane.add(comboBox, BorderLayout.NORTH);
    final JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        textArea.append("Selected: " + comboBox.getSelectedItem());
        textArea.append(", Position: " + comboBox.getSelectedIndex());
        textArea.append(System.getProperty("line.separator"));
      }
    };
    comboBox.addActionListener(actionListener);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Font Chooser ComboBox

 
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FontComboBox extends JFrame implements ActionListener {
  JLabel fontLabel = new JLabel(
      "The quick brown fox jumps over the lazy dog.");
  private JComboBox fontComboBox;
  public FontComboBox() {
    setTitle("ComboBoxTest");
    setSize(300, 200);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    fontComboBox = new JComboBox();
    fontComboBox.setEditable(true);
    fontComboBox.addItem("Serif");
    fontComboBox.addItem("SansSerif");
    fontComboBox.addItem("Monospaced");
    fontComboBox.addItem("Dialog");
    fontComboBox.addItem("DialogInput");
    fontComboBox.addActionListener(this);
    JPanel p = new JPanel();
    p.add(fontComboBox);
    getContentPane().add(p, "North");
    getContentPane().add(fontLabel, "Center");
  }
  public void actionPerformed(ActionEvent evt) {
    JComboBox source = (JComboBox) evt.getSource();
    String item = (String) source.getSelectedItem();
    fontLabel.setFont(new Font(item, Font.PLAIN, 12));
  }
  public static void main(String[] args) {
    JFrame frame = new FontComboBox();
    frame.show();
  }
}





Getting and Setting the Selected Item in a JComboBox Component

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    // Get current value
    Object obj = cb.getSelectedItem(); 
    // Set a new value
    cb.setSelectedItem("item2");
    obj = cb.getSelectedItem(); 
    // If the new value is not in the list of valid items, the call is ignored
    cb.setSelectedItem("item3");
    obj = cb.getSelectedItem(); 
  }
}





Getting the Items in a JComboBox Component

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2", "item3" };
    JComboBox cb = new JComboBox(items);
    // Get number of items
    int num = cb.getItemCount();
    // Get items
    for (int i = 0; i < num; i++) {
      Object item = cb.getItemAt(i);
    }
  }
}





If the combobox is editable, the new value can be any value

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a read-only combobox
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.setEditable(true);
    cb.setSelectedItem("item3");
    Object obj = cb.getSelectedItem(); 
  }
}





Listening for Action Events from a JComboBox Component

 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.setEditable(true);
    // Create and register listener
    MyActionListener actionListener = new MyActionListener();
    cb.addActionListener(actionListener);
  }
}
class MyActionListener implements ActionListener {
  Object oldItem;
  public void actionPerformed(ActionEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
    Object newItem = cb.getSelectedItem();
    boolean same = newItem.equals(oldItem);
    oldItem = newItem;
    if ("comboBoxEdited".equals(evt.getActionCommand())) {
      // User has typed in a string; only possible with an editable combobox
    } else if ("comboBoxChanged".equals(evt.getActionCommand())) {
      // User has selected an item; it may be the same item
    }
  }
}





Listening for Changes to the Selected Item in a JComboBox Component

 
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.setEditable(true);
    MyItemListener actionListener = new MyItemListener();
    cb.addItemListener(actionListener);
  }
}
class MyItemListener implements ItemListener {
  // This method is called only if a new item has been selected.
  public void itemStateChanged(ItemEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
    Object item = evt.getItem();
    if (evt.getStateChange() == ItemEvent.SELECTED) {
      // Item was just selected
    } else if (evt.getStateChange() == ItemEvent.DESELECTED) {
      // Item is no longer selected
    }
  }
}





MultiKey Combo

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ruboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.Timer;
public class MultiKeyCombo {
  public static void main(String args[]) {
    String labels[] = { "One", "Only", "Once", "Okay", "oneself",
        "onlooker", "Onslaught", "Onyx", "onus", "onward" };
    JFrame f = new JFrame("Example JList");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComboBox jc = new JComboBox(labels);
    MultiKeySelectionManager mk = new MultiKeySelectionManager();
    jc.setKeySelectionManager(mk);
    //    jc.setKeySelectionManager (new JComboBox.KeySelectionManager() {
    //      public int selectionForKey (char aKey, ComboBoxModel aModel) {
    //        return -1;
    //      }
    //    });
    Container c = f.getContentPane();
    c.add(jc, BorderLayout.NORTH);
    f.setSize(200, 200);
    f.setVisible(true);
  }
}
class MultiKeySelectionManager implements JComboBox.KeySelectionManager {
  private StringBuffer currentSearch = new StringBuffer();
  private Timer resetTimer;
  private final static int RESET_DELAY = 3000;
  public MultiKeySelectionManager() {
    resetTimer = new Timer(RESET_DELAY, new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        currentSearch.setLength(0);
      }
    });
  }
  public int selectionForKey(char aKey, ComboBoxModel aModel) {
    // Reset if invalid character
    if (aKey == KeyEvent.CHAR_UNDEFINED) {
      currentSearch.setLength(0);
      return -1;
    }
    // Since search, don"t reset search
    resetTimer.stop();
    // Convert input to uppercase
    char key = Character.toUpperCase(aKey);
    // Build up search string
    currentSearch.append(key);
    // Find selected position within model to starting searching from
    Object selectedElement = aModel.getSelectedItem();
    int selectedIndex = -1;
    if (selectedElement != null) {
      for (int i = 0, n = aModel.getSize(); i < n; i++) {
        if (aModel.getElementAt(i) == selectedElement) {
          selectedIndex = i;
          break;
        }
      }
    }
    boolean found = false;
    String search = currentSearch.toString();
    // Search from selected forward, wrap back to beginning if not found
    for (int i = 0, n = aModel.getSize(); i < n; i++) {
      String element = aModel.getElementAt(selectedIndex).toString()
          .toUpperCase();
      if (element.startsWith(search)) {
        found = true;
        break;
      }
      selectedIndex++;
      if (selectedIndex == n) {
        selectedIndex = 0; // wrap
      }
    }
    // Restart timer
    resetTimer.start();
    return (found ? selectedIndex : -1);
  }
}





PopupCombo Sample

 
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.plaf.ruboBoxUI;
import javax.swing.plaf.ruponentUI;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicComboBoxUI;
public class PopupComboSample {
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","I", "J" };
    JFrame frame = new JFrame("Popup JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    JComboBox comboBox = new JComboBox(labels);
    comboBox.setMaximumRowCount(5);
    comboBox.setUI((ComboBoxUI) MyComboBoxUI.createUI(comboBox));
    contentPane.add(comboBox, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
    comboBox.showPopup();
  }
  static class MyComboBoxUI extends BasicComboBoxUI {
    public static ComponentUI createUI(JComponent c) {
      return new MyComboBoxUI();
    }
    protected JButton createArrowButton() {
      JButton button = new BasicArrowButton(BasicArrowButton.EAST);
      return button;
    }
  }
}





Remove all items

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.removeAllItems();
  }
}





Remove first item

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.removeItemAt(0);
  }
}





Remove the last item

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    cb.removeItemAt(cb.getItemCount() - 1);
  }
}





Selecting an Item in a JComboBox Component with Multiple Keystrokes

 
import javax.swing.ruboBoxModel;
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "A", "B", "B", "C", "C" };
    JComboBox cb = new JComboBox(items);
    cb.setKeySelectionManager(new MyKeySelectionManager());
  }
}
class MyKeySelectionManager implements JComboBox.KeySelectionManager {
  long lastKeyTime = 0;
  String pattern = "";
  public int selectionForKey(char aKey, ComboBoxModel model) {
    int selIx = 01;
    Object sel = model.getSelectedItem();
    if (sel != null) {
      for (int i = 0; i < model.getSize(); i++) {
        if (sel.equals(model.getElementAt(i))) {
          selIx = i;
          break;
        }
      }
    }
    long curTime = System.currentTimeMillis();
    if (curTime - lastKeyTime < 300) {
      pattern += ("" + aKey).toLowerCase();
    } else {
      pattern = ("" + aKey).toLowerCase();
    }
    lastKeyTime = curTime;
    for (int i = selIx + 1; i < model.getSize(); i++) {
      String s = model.getElementAt(i).toString().toLowerCase();
      if (s.startsWith(pattern)) {
        return i;
      }
    }
    for (int i = 0; i < selIx; i++) {
      if (model.getElementAt(i) != null) {
        String s = model.getElementAt(i).toString().toLowerCase();
        if (s.startsWith(pattern)) {
          return i;
        }
      }
    }
    return -1;
  }
}





Selecting Combo Sample

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.ItemSelectable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SelectingComboSample {
  static private String selectedString(ItemSelectable is) {
    Object selected[] = is.getSelectedObjects();
    return ((selected.length == 0) ? "null" : (String) selected[0]);
  }
  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D","E", "F", "G", "H","J", "I" };
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    JComboBox comboBox = new JComboBox(labels);
    contentPane.add(comboBox, BorderLayout.SOUTH);
    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane sp = new JScrollPane(textArea);
    contentPane.add(sp, BorderLayout.CENTER);
    ItemListener itemListener = new ItemListener() {
      public void itemStateChanged(ItemEvent itemEvent) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        int state = itemEvent.getStateChange();
        String stateString = ((state == ItemEvent.SELECTED) ? "Selected": "Deselected");
        pw.print("Item: " + itemEvent.getItem());
        pw.print(", State: " + stateString);
        ItemSelectable is = itemEvent.getItemSelectable();
        pw.print(", Selected: " + selectedString(is));
        pw.println();
        textArea.append(sw.toString());
      }
    };
    comboBox.addItemListener(itemListener);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.print("Command: " + actionEvent.getActionCommand());
        ItemSelectable is = (ItemSelectable) actionEvent.getSource();
        pw.print(", Selected: " + selectedString(is));
        pw.println();
        textArea.append(sw.toString());
      }
    };
    comboBox.addActionListener(actionListener);
    frame.setSize(400, 200);
    frame.setVisible(true);
  }
}





Select the combobox by choose the nearby label

 
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class LabelForComboBox extends JPanel {
  public LabelForComboBox() {
    JLabel lbl = new JLabel("Color:");
    lbl.setDisplayedMnemonic("c");
    add(lbl);
    add(Box.createHorizontalStrut(20));
    JComboBox cbColor = new JComboBox();
    cbColor.addItem("red");
    cbColor.addItem("blue");
    lbl.setLabelFor(cbColor);
    add(cbColor);
  }
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    f.getContentPane().add(new LabelForComboBox());
    f.pack();
    f.setSize(new Dimension(300, 200));
    f.show();
  }
}





Setting the Number of Visible Items in the Menu of a JComboBox Component

 
import javax.swing.JComboBox;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = new String[50];
    for (int i = 0; i < items.length; i++) {
      items[i] = "" + Math.random();
    }
    JComboBox cb = new JComboBox(items);
    // Retrieve the current max visible rows
    int maxVisibleRows = cb.getMaximumRowCount();
    // Change the current max visible rows
    maxVisibleRows = 20;
    cb.setMaximumRowCount(maxVisibleRows);
  }
}





Using drop-down lists

 
// : c14:ComboBoxes.java
// Using drop-down lists.
// <applet code=ComboBoxes width=200 height=125></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class ComboBoxes extends JApplet {
  private String[] description = { "Ebullient", "Obtuse", "Recalcitrant",
      "Brilliant", "Somnescent", "Timorous", "Florid", "Putrescent" };
  private JTextField t = new JTextField(15);
  private JComboBox c = new JComboBox();
  private JButton b = new JButton("Add items");
  private int count = 0;
  public void init() {
    for (int i = 0; i < 4; i++)
      c.addItem(description[count++]);
    t.setEditable(false);
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (count < description.length)
          c.addItem(description[count++]);
      }
    });
    c.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        t.setText("index: " + c.getSelectedIndex() + "   "
            + ((JComboBox) e.getSource()).getSelectedItem());
      }
    });
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(t);
    cp.add(c);
    cp.add(b);
  }
  public static void main(String[] args) {
    run(new ComboBoxes(), 200, 125);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~