JComboxBox is a Swing component that renders a drop-down list of choices and lets the user selects one item from the list. Here are some screenshots of this component in default Java look-and-feel and Windows look-and-feel:
That shows three combo boxes with each in two states:
Here’s a quick example showing how to create the first combo box shown in the above screenshot:
Keep in mind that we have to override the toString() method to return a textual representation of the Job class, so the JComboBox class can use it to show item’s name in the drop-down list.
Learn Swing in Swing: A Beginner's Guide
The following screenshot shows how an editable combo box looks like:
As we can see, the user can type “Spring framework” into the combo box as the drop-down list does not contain that title.
Related Course: Java Swing (GUI) Programming: From Beginner to Expert
This custom model class, MyComboBoxModel extends the DefaultComboBoxModel class for the custom type Job, and overrides its getSelectedItem() method to control how a selected item would be returned. And we can pass an instance of this model class when creating a new JComboBox object as follows:
Or we can set the custom model for the combo box after it’s created like this:
The ActionEvent will be fired whenever an item is selected from the drop-down list, and perhaps this is the only useful action which we’re interested when working with JComboBox.
- Before selecting an item: display of the combo box when there is no action on it (e.g. selecting an item). The combo box is composed of a text and a down-arrow button that lets the user selects an item for the list.
- After selecting an item: display of the combo box when the user is making a selection, a drop-down list of choices is shown up to show available options.
String[] bookTitles = new String[] {"Effective Java", "Head First Java", "Thinking in Java", "Java for Dummies"}; JComboBox<String> bookList = new JComboBox<>(bookTitles); // add to the parent container (e.g. a JFrame): add(bookList); // get the selected item: String selectedBook = (String) bookList.getSelectedItem(); System.out.println("You seleted the book: " + selectedBook);That’s for a typical usage of the JComboBox component. Now let’s see other stuffs we can do with this component in details.
1. Creating a new JComboBox component
Basically, we should specify type of the items which the combo box will hold using the generic syntax (the JComboBox class can have parameterized type since Java 7), for example:JComboBox<String> myTitles = new JComboBox<String>(); JComboBox<Integer> myNumbers = new JComboBox<Integer>();
There are several ways to construct a new combo box, according to its constructors provided:
- Creating a default, empty JComboBox then add items later using the addItem()method:
123456789
// create an empty combo box with items of type String
JComboBox<String> comboLanguage =
new
JComboBox<String>();
// add items to the combo box
comboLanguage.addItem(
"English"
);
comboLanguage.addItem(
"French"
);
comboLanguage.addItem(
"Spanish"
);
comboLanguage.addItem(
"Japanese"
);
comboLanguage.addItem(
"Chinese"
);
- Creating a JComboBox with an array of items:
12345
// define items in a String array:
String[] languages =
new
String[] {
"English"
,
"French"
,
"Spanish"
,
"Japanese"
,
"Chinese"
};
// create a combo box with the fixed array:
JComboBox<String> comboLanguage =
new
JComboBox<String>(languages);
- Creating a JComboBoxwith a vector of items:
12345678910
// define items in a vector collection:
Vector<String> languages =
new
Vector<String>();
languages.addElement(
"English"
);
languages.addElement(
"French"
);
languages.addElement(
"Spanish"
);
languages.addElement(
"Japanese"
);
languages.addElement(
"Chinese"
);
// create a combo box with the given vector
JComboBox<String> comboLanguage =
new
JComboBox<String>(languages);
- Creating a JComboBox with items of a custom type:
Generally a combo box can hold items of any type. If the type of the items is a custom object other than String, then the object’s toString() method will be used to get name of the items in the drop-down list. Following is an example that creates a combo box with items of a custom type Job:
1
2
3
4
5
| JComboBox<Job> jobList = new JComboBox<Job>(); jobList.addItem( new Job( "Developer" )); jobList.addItem( new Job( "Designer" )); jobList.addItem( new Job( "Architect" )); jobList.addItem( new Job( "Team Leader" )); |
The class Job is defined as follows:
1
2
3
4
5
6
7
8
9
10
11
| class Job { private String jobTitle; public Job(String jobTitle) { this .jobTitle = jobTitle; } public String toString() { return this .jobTitle; } } |
2. Creating an editable combo box
By default, a JComboBox component is created in read-only mode, which means the user can only pick one item from the fixed options in the drop-down list. What if we want to allow the user to provide his own option besides the fixed ones? Well, in this case we can simply use the setEditable() method to make the combo box editable:
1
2
3
4
| // code to create a combo box as above... // make it editable myComboBox.setEditable( true ); |
3. Using a custom ComboBoxModel
Besides using an array or a vector as items for the combo box (in this case, the JComboBox will create a default model), it’s also possible to use a custom data model in order to have more control over the items (especially for items of a custom type). To create a custom model class for the combo box, create a class that implements the interface ComboBoxModel and override the interface’s methods. However we don’t need to implement the ComboBoxModel interface directly, as Swing provides a default implementation class called DefaultComboBoxModel which already does the basic stuffs. Here’s an example of a custom model class for combo box:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| class MyComboBoxModel extends DefaultComboBoxModel<Job> { public MyComboBoxModel(Job[] items) { super (items); } @Override public Job getSelectedItem() { Job selectedJob = (Job) super .getSelectedItem(); // do something with this job before returning... return selectedJob; } } |
1
2
3
4
5
6
| Job[] jobs = new Job[] { new Job( "Developer" ), new Job( "Designer" ), new Job( "Tester" ) }; MyComboBoxModel myModel = new MyComboBoxModel(jobs); JComboBox<Job> jobList = new JComboBox<Job>(myModel); |
1
2
| JComboBox<Job> jobList = new JComboBox<Job>(); jobList.setModel(myModel); |
4. Adding the combo box to a container
After created, the combo box should be added to a container like a JFrame or JPanel which can have different layout managers. For example:- Adding the combo box to a JFrame with FlowLayout manager:
123
theFrame.setLayout(
new
FlowLayout());
theFrame.add(myComboBox);
- Adding the combo box to a JPanel with BorderLayout manager:
1
thePanel.add(myComboBox, BorderLayout.CENTER);
- Adding the combo box to a JPanel with GridBagLayout manager:
1
2
3
4
5
| thePanel.setLayout( new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); // set constraints details... constraints.gridx = 1 ; thePanel.add(myComboBox, constraints); |
5. Working with items in the combo box
The common operations we can do with items in the combo box are adding, removing, setting selected item, getting selected item, and getting total number of items. Here are some examples:- Adding new items to the combo box (using the addItem()method):12345678
String[] bookTitles =
new
String[] {
"Effective Java"
,
"Head First Java"
,
"Thinking in Java"
};
JComboBox<String> bookList =
new
JComboBox<String>(bookTitles);
// add more books
bookList.addItem(
"Java Generics and Collections"
);
bookList.addItem(
"Beginnning Java 7"
);
bookList.addItem(
"Java I/O"
);
- Adding new items if using a custom model (using the addElement() method of the DefaultComboBoxModel class) :
123456
Job[] jobs =
new
Job[] {
new
Job(
"Developer"
),
new
Job(
"Designer"
),
new
Job(
"Tester"
)};
MyComboBoxModel myModel =
new
MyComboBoxModel(jobs);
myModel.addElement(
new
Job(
"Consultant"
));
myModel.addElement(
new
Job(
"Manager"
));
JComboBox<Job> jobList =
new
JComboBox<Job>(myModel);
- Removing items from the combo box (using the removeItem() or removeItemAt()methods):
12345678910
// remove an item of type String
bookList.removeItem(
"Thinking in Java"
);
// remove an item of a custom type Job
// the Job class must override the equals() method
Job consultantJob =
new
Job(
"Consultant"
);
jobList.removeItem(consultantJob);
// remove an item at a given index:
jobList.removeItemAt(
2
);
- Removing all items (using the removeAllItems()method):
1
bookList.removeAllItems();
- Setting selected item (using the setSelectedItem() or setSelectedIndex()methods):
12345678910
// set selected item of type String:
bookList.setSelectedItem(
"Head First Java"
);
// set selected item of a custom type Job:
// the Job class must override the equals() method
Job consultantJob =
new
Job(
"Consultant"
);
jobList.setSelectedItem(consultantJob);
// set selected item at a given index:
jobList.setSelectedIndex(
1
);
- Getting selected item (using the getSelectedItem() or getSelectedIndex()methods):
1234567
// get the selected item as an object
String selectedBook = (String) bookList.getSelectedItem();
Job selectedJob = (Job) jobList.getSelectedItem();
// get the selected item as an index:
int
selectedIndex = jobList.getSelectedIndex();
- Getting an item at a specified index (using the getItemAt()method):
12
// get the 4th item in the list
String item4th = bookList.getItemAt(
3
);
- Getting total number of items in the combo box (using the getItemCount() method):
1
2
| // get total number of items: int totalBooks = bookList.getItemCount(); |
6. Adding an event listener
Basically we can handle the event that happens when the user is selecting an item from the combo box’s drop-down list. Here’s an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| bookList.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JComboBox<String> combo = (JComboBox<String>) event.getSource(); String selectedBook = (String) combo.getSelectedItem(); if (selectedBook.equals( "Effective Java" )) { System.out.println( "Good choice!" ); } else if (selectedBook.equals( "Head First Java" )) { System.out.println( "Nice pick, too!" ); } } }); |
7. Customizing combo box’s appearance
There are few things we can do to change the combo box’s default appearance out-of-the-box such as changing font style, font color for the selected item’s text:And limit the maximum number of items displayed in the drop-down list:
12bookList.setForeground(Color.BLUE);
bookList.setFont(
new
Font(
"Arial"
, Font.BOLD,
14
));
In this case, if the combo box contains more than 5 items, then the drop-down list will show only the first 5 ones and add a vertical scroll bar to navigating the rest items. This would be useful if we have a combo box with many items, thus such limitation is needed.
1bookList.setMaximumRowCount(
5
);
Here’s the screenshot of a combo box whose appearance is customized as above:8. A demo program for JComboBox
For your reference, we created a small Swing program to demo the usage of the JComboBox component. The program looks like this:It contains an editable combo box and two buttons. You can type new title into the combo box and hit Enter, and the new title will be added to the drop-down list. On clicking the Select button, a message dialog appears saying what is the selected book:
Java JComboBox Example
Output:
Java JComboBox Example with ActionListener
Output:
IN THE NEXT TUTORIAL, WE SHALL DISCUSS ON JCOMBOBOX WITH CUSTOM GUI
No comments:
Post a Comment