Java Swing JComboBox
2018-01-09 19:23 更新
Java Swing教程 - Java Swing JComboBox
A JComboBox< E> 是一个Swing组件,允许我们从一个选择列表中做一个选择。
JComboBox可以有一个可编辑的字段,我们可以键入一个新的选择值。
类型参数E是它包含的元素的类型。
我们可以通过在其构造函数中传递选择列表来创建一个JComboBox。
以下代码使用String数组作为选择列表。
String[] sList = new String[]{"Spring", "Summer", "Fall", "Winter"}; JComboBox<String> seasons = new JComboBox<>(sList);
下面的代码使用String的Vector作为选择列表
Vector<String> myList = new Vector<>(4); myList.add("Spring"); myList.add("Summer"); myList.add("Fall"); myList.add("Winter"); JComboBox<String> seasons2 = new JComboBox<>(myList);
下表列出了JComboBox类的常用方法。
ID | 方法/说明 |
---|---|
1 | void addItem(E item)将项目添加到列表。 将调用所添加对象的toString()方法,并显示返回的字符串。 |
2 | E getItemAt(int index)从列表返回指定索引处的项目。 |
3 | int getItemCount()返回选项列表中的项目数。 |
4 | int getSelectedIndex()返回所选项目的索引。 如果所选项目不在列表中,则返回-1。 |
5 | Object getSelectedItem()返回当前选定的项目。 如果没有选择,则返回null。 |
6 | void insertItemAt(E item,int index)在列表中指定的索引处插入指定的项目。 |
7 | boolean isEditable()如果JComboBox是可编辑的,则返回true。 否则,它返回false。 默认情况下,JComboBox是不可编辑的。 |
8 | void removeAllItems()从列表中删除所有项目。 |
9 | void removeItem(Object item)从列表中删除指定的项目。 |
10 | void removeItemAt(int index)删除指定索引处的项目。 |
11 | void setEditable(boolean editable)如果指定的可编辑参数为true,则JComboBox是可编辑的。 否则,它是不可编辑的。 |
12 | void setSelectedIndex(int index)选择列表中指定索引处的项目。 如果指定的索引为-1,它将清除选择。 |
13 | void setSelectedIndex(int index)选择列表中指定索引处的项目。 如果指定的索引为-1,它将清除选择。... |
选择事件
要处理JComboBox中的所选或取消选择的事件,请向其中添加一个项目侦听器。每当选择或取消选择项目时,都会通知项目侦听器。
以下代码显示了如何向JComboBox添加项目监听器。
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ItemEvent; // w ww . j ava 2s .com import javax.swing.JComboBox; import javax.swing.JFrame; public class Main extends JFrame { public Main() { this.setDefaultCloseOperation(EXIT_ON_CLOSE); String[] sList = new String[] { "Spring", "Summer", "Fall", "Winter" }; JComboBox<String> seasons = new JComboBox<>(sList); seasons.addItemListener((ItemEvent e) -> { Object item = e.getItem(); if (e.getStateChange() == ItemEvent.SELECTED) { // Item has been selected System.out.println(item + " has been selected"); } else if (e.getStateChange() == ItemEvent.DESELECTED) { // Item has been deselected System.out.println(item + " has been deselected"); } }); Container contentPane = this.getContentPane(); contentPane.add(seasons, BorderLayout.CENTER); } public static void main(String[] args) { Main bf = new Main(); bf.pack(); bf.setVisible(true); } }
ActionListener
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /* w w w .j a v a2s .c o m*/ 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(); } }
在两个JComboBox之间共享数据模型
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // w w w . java 2 s . com 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); } }
使用KeySelectionManager监听键盘事件
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // www .jav a 2s. c om 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); } }
颜色组合框编辑器
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; //from w ww.j a v a 2 s. c o m import javax.swing.ComboBoxEditor; 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 Main { 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); } }
Combobox单元格渲染器
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; //from w w w .j av a 2s.c o m 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 Main { 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); } }
以上内容是否对您有帮助:
更多建议: