Java Tutorial/Swing/JComboBox — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:33, 31 мая 2010
Содержание
- 1 A Color Combo Box Editor
- 2 Add an item after the first item
- 3 Add an item to the end of the list
- 4 Adding and Removing an Item in a JComboBox Component
- 5 Add Items to JComboBox
- 6 Combobox cell renderer
- 7 Creating JComboBox Components
- 8 Customizing a JComboBox Look and Feel
- 9 Custom JComboBox Pop-up Button
- 10 Determining If the Menu of a JComboBox Component Is Visible
- 11 Determining When the Menu of a JComboBox Component Is Displayed
- 12 Displaying the Menu in a JComboBox Component Using a Keystroke
- 13 Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique
- 14 Editable JComboBox
- 15 Editing JComboBox Elements
- 16 Get Model from JComboBox and set it to JList
- 17 Get selected Item from JComboBox
- 18 Getting and Setting the Selected Item in a JComboBox Component
- 19 Getting the Items in a JComboBox Component
- 20 If the combobox is editable, the new value can be any value
- 21 JComboBox Using the Custom Model
- 22 Listening for Action Events from a JComboBox Component
- 23 Listening for Changes to the Selected Item in a JComboBox Component
- 24 Listening to Keyboard Events with a KeySelectionManager
- 25 Listen to JComboBox with ItemListener
- 26 Remove all items
- 27 Remove first item
- 28 Remove the last item
- 29 Selecting an Item in a JComboBox Component with Multiple Keystrokes
- 30 Setting ComboBox Editor and ComboBox Renderer
- 31 Setting the Number of Visible Items in the Menu of a JComboBox Component
- 32 Sharing the Data Model between two JComboBoxes
A Color Combo Box Editor
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ruboBoxEditor;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.EventListenerList;
class ColorComboBoxEditor implements ComboBoxEditor {
final protected JButton editor;
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 {
Color color = Color.decode(newValue.toString());
editor.setBackground(color);
} catch (NumberFormatException e) {
}
}
}
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);
}
}
}
}
public class ColorComboBoxEditorDemo {
public static void main(String args[]) {
Color colors[] = { Color.RED, Color.BLUE, Color.BLACK, Color.WHITE };
JFrame frame = new JFrame("Editable JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox comboBox = new JComboBox(colors);
comboBox.setEditable(true);
comboBox.setEditor(new ColorComboBoxEditor(Color.RED));
frame.add(comboBox, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
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);
}
}
Add Items to JComboBox
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class AddingItemToComboBox {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox jComboBox1 = new JComboBox();
jComboBox1.addItem("asdf");
Object cmboitem = jComboBox1.getSelectedItem();
System.out.println(cmboitem);
frame.add(jComboBox1);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Combobox cell renderer
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
class ComplexCellRenderer implements ListCellRenderer {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
Font theFont = null;
Color theForeground = null;
Icon theIcon = null;
String theText = null;
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value instanceof Object[]) {
Object values[] = (Object[]) value;
theFont = (Font) values[0];
theForeground = (Color) values[1];
theIcon = (Icon) values[2];
theText = (String) values[3];
} else {
theFont = list.getFont();
theForeground = list.getForeground();
theText = "";
}
if (!isSelected) {
renderer.setForeground(theForeground);
}
if (theIcon != null) {
renderer.setIcon(theIcon);
}
renderer.setText(theText);
renderer.setFont(theFont);
return renderer;
}
}
public class ComplexRenderingSample {
public static void main(String args[]) {
Object elements[][] = {
{ new Font("Helvetica", Font.PLAIN, 20), Color.RED, new MyIcon(), "A" },
{ new Font("TimesRoman", Font.BOLD, 14), Color.BLUE, new MyIcon(), "A" },
{ new Font("Courier", Font.ITALIC, 18), Color.GREEN, new MyIcon(), "A" },
{ new Font("Helvetica", Font.BOLD | Font.ITALIC, 12), Color.GRAY, new MyIcon(), "A" },
{ new Font("TimesRoman", Font.PLAIN, 32), Color.PINK, new MyIcon(), "A" },
{ new Font("Courier", Font.BOLD, 16), Color.YELLOW, new MyIcon(), "A" },
{ new Font("Helvetica", Font.ITALIC, 8), Color.DARK_GRAY, new MyIcon(), "A" } };
JFrame frame = new JFrame("Complex Renderer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ListCellRenderer renderer = new ComplexCellRenderer();
JComboBox comboBox = new JComboBox(elements);
comboBox.setRenderer(renderer);
frame.add(comboBox, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class MyIcon implements Icon {
public MyIcon() {
}
public int getIconHeight() {
return 20;
}
public int getIconWidth() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.RED);
g.drawRect(0, 0, 25, 25);
}
}
Creating JComboBox Components
public JComboBox()
JComboBox comboBox = new JComboBox();
public JComboBox(Object listData[])
String labels[] = { "A", "B", "C", "D", "E"};
JComboBox comboBox = new JComboBox(labels);
public JComboBox(Vector listData)
Vector vector = aBufferedImage.getSources();
JComboBox comboBox = new JComboBox(vector);
public JComboBox(ComboBoxModel model)
ResultSet results = aJDBCStatement.executeQuery("SELECT columnName FROM tableName");
DefaultComboBoxModel model = new DefaultComboBoxModel();
while (result.next())
model.addElement(results.getString(1));
JComboBox comboBox = new JComboBox(model);
Customizing a JComboBox Look and Feel
Property StringObject TypeComboBox.actionMapActionMapComboBox.ancestorInputMapInputMapComboBox.backgroundColorComboBox.borderBorderComboBox.buttonBackgroundColorComboBox.buttonDarkShadowColorComboBox.buttonHighlightColorComboBox.buttonShadowColorComboBox.controlColorComboBox.controlForegroundColorComboBox.disabledBackgroundColorComboBox.disabledForegroundColorComboBox.fontFontComboBox.foregroundColorComboBox.rendererUseListColorsBooleanComboBox.selectionBackgroundColorComboBox.selectionForegroundColorComboBox.showPopupOnNavigationBooleanComboBox.timeFactorLongComboBox.togglePopupTextStringComboBoxUIString
Custom JComboBox Pop-up Button
import java.awt.BorderLayout;
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" };
JFrame frame = new JFrame("Popup JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox comboBox = new JComboBox(labels);
comboBox.setUI((ComboBoxUI) MyComboBoxUI.createUI(comboBox));
frame.add(comboBox, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
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;
}
}
}
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 JComboBox
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;
public class Main extends JFrame {
JComboBox combo = new JComboBox();
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
combo.addItem("A");
combo.addItem("H");
combo.addItem("P");
combo.setEditable(true);
System.out.println("#items=" + combo.getItemCount());
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Selected index=" + combo.getSelectedIndex()
+ " Selected item=" + combo.getSelectedItem());
}
});
getContentPane().add(combo);
pack();
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
Editing JComboBox Elements
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class EditComboBox {
public static void main(String args[]) {
String labels[] = { "A", "B", "C", "D", "E", "F", "G" };
JFrame frame = new JFrame("Editable JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox comboBox = new JComboBox(labels);
comboBox.setMaximumRowCount(5);
comboBox.setEditable(true);
frame.add(comboBox, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: " + comboBox.getSelectedItem());
System.out.println(", Position: " + comboBox.getSelectedIndex());
}
};
comboBox.addActionListener(actionListener);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Get Model from JComboBox and set it to JList
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Lister {
public static void main(String[] args) {
JFrame frame = new JFrame("Lister v1.0");
String[] items = { "A", "B", "C" };
JComboBox comboBox = new JComboBox(items);
comboBox.setEditable(true);
final JList list = new JList(comboBox.getModel());
JButton button = new JButton("Per favore");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Object[] selection = list.getSelectedValues();
for (Object s : selection)
System.out.println(s);
}
});
JPanel comboPanel = new JPanel();
comboPanel.add(comboBox);
frame.add(comboPanel, BorderLayout.NORTH);
frame.add(new JScrollPane(list), BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Get selected Item from JComboBox
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
public class GettingSettingSelectedItem {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jButton1 = new JButton("Button");
String[] mystring = { "Java", "JBuilder", "JFC", "Swing" };
final JList jList1 = new JList(mystring);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
Object contents = jList1.getSelectedValue();
System.out.println(contents);
}
});
frame.add(jList1, "Center");
frame.add(jButton1,"South");
frame.setSize(300, 200);
frame.setVisible(true);
}
}
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();
}
}
JComboBox Using the Custom Model
import javax.swing.AbstractListModel;
import javax.swing.ruboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
class MyComboBoxModel extends AbstractListModel implements ComboBoxModel {
String[] ComputerComps = { "Monitor", "Key Board", "Mouse", "Joy Stick", "Modem", "CD ROM",
"RAM Chip", "Diskette" };
String selection = null;
public Object getElementAt(int index) {
return ComputerComps[index];
}
public int getSize() {
return ComputerComps.length;
}
public void setSelectedItem(Object anItem) {
selection = (String) anItem; // to select and register an
} // item from the pull-down list
// Methods implemented from the interface ComboBoxModel
public Object getSelectedItem() {
return selection; // to add the selection to the combo box
}
}
public class JComboBoxModel {
public static void main(String[] a){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox cbox = new JComboBox(new MyComboBoxModel());
cbox.setMaximumRowCount(5);
frame.add(cbox);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
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
}
}
}
Listening to Keyboard Events with a KeySelectionManager
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SelectingComboSample {
public static void main(String args[]) {
String labels[] = { "A", "B", "C", "D", "E", "F" };
JFrame frame = new JFrame("Selecting JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox comboBox = new JComboBox(labels);
frame.add(comboBox, BorderLayout.SOUTH);
JComboBox.KeySelectionManager manager =
new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
System.out.println(aKey);
return -1;
}
};
comboBox.setKeySelectionManager(manager);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
Listen to JComboBox with ItemListener
You can listen with an ActionListener or an ItemListener to find out when the selected item of the JComboBox changes.
import java.awt.BorderLayout;
import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ItemListenerSelectingComboSample {
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" };
JFrame frame = new JFrame("Selecting JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox comboBox = new JComboBox(labels);
frame.add(comboBox, BorderLayout.SOUTH);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
System.out.println((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
System.out.println("Item: " + itemEvent.getItem());
ItemSelectable is = itemEvent.getItemSelectable();
System.out.println(", Selected: " + selectedString(is));
}
};
comboBox.addItemListener(itemListener);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
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;
}
}
Setting ComboBox Editor and ComboBox Renderer
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
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.border.LineBorder;
import javax.swing.event.EventListenerList;
class ColorComboBoxEditor implements ComboBoxEditor {
final protected JButton editor;
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() {
}
public void setItem(Object newValue) {
if (newValue instanceof Color) {
Color color = (Color) newValue;
editor.setBackground(color);
} else {
try {
Color color = Color.decode(newValue.toString());
editor.setBackground(color);
} catch (NumberFormatException e) {
}
}
}
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);
}
}
}
}
class ColorCellRenderer implements ListCellRenderer {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
// Width doesn"t matter as the combo box 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);
}
if(cellHasFocus || isSelected){
renderer.setBorder(new LineBorder(Color.DARK_GRAY));
}else{
renderer.setBorder(null);
}
renderer.setPreferredSize(preferredSize);
return renderer;
}
}
public class ColorComboBoxEditorRendererDemo {
public static void main(String args[]) {
Color colors[] = { Color.BLACK, Color.BLUE, Color.GREEN, Color.RED, Color.WHITE, Color.YELLOW };
JFrame frame = new JFrame("Color JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox comboBox = new JComboBox(colors);
comboBox.setEditable(true);
comboBox.setRenderer(new ColorCellRenderer());
Color color = (Color) comboBox.getSelectedItem();
ComboBoxEditor editor = new ColorComboBoxEditor(color);
comboBox.setEditor(editor);
frame.add(comboBox, BorderLayout.NORTH);
final JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground((Color) comboBox.getSelectedItem());
frame.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);
}
}
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);
}
}
Sharing the Data Model between two JComboBoxes
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SharedDataBetweenComboBoxSample {
public static void main(String args[]) {
final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };
final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);
JFrame frame = new JFrame("Shared Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JComboBox comboBox1 = new JComboBox(model);
comboBox1.setEditable(true);
JComboBox comboBox2 = new JComboBox(model);
comboBox2.setEditable(true);
panel.add(comboBox1);
panel.add(comboBox2);
frame.add(panel, BorderLayout.NORTH);
JButton button = new JButton("Add");
frame.add(button, BorderLayout.SOUTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
model.addElement("New Added");
}
};
button.addActionListener(actionListener);
frame.setSize(300, 200);
frame.setVisible(true);
}
}