Java Reference
In-Depth Information
Listing 13-13. Editable JComboBox Sample
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class EditComboBox {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
String labels[] = {"Chardonnay", "Sauvignon", "Riesling", "Cabernet",
"Zinfandel", "Merlot", "Pinot Noir", "Sauvignon Blanc", "Syrah",
"Gewürztraminer"};
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);
final JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
frame.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);
}
};
EventQueue.invokeLater(runner);
}
}
By default, the input field provided for editing is a JTextField . The default JTextField
serves as a good editor if your data model consists of text strings. However, once your model
contains a different type of object (for example, colors), you need to provide a different editor.
By default, once you type in the text field (editing the results of toString() for your element),
the object is treated as a String . Technically, a different editor isn't always necessary. If you can
Search WWH ::




Custom Search