Bitcoin

Bitcoin
Bitcoin

JComboBox Java

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:
ComboBox samples
That shows three combo boxes with each in two states:
    • 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.
The combo box can be read only (the first two in the above screenshot) or editable (the last one). An editable combo box allows the user to type a different value other than the fixed ones.
Here’s a quick example showing how to create the first combo box shown in the above screenshot:
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: 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 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: 
    1
    2
    3
    4
    5
    // 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: 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 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;
    }
}
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

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);
The following screenshot shows how an editable combo box looks like:
 editable combobox
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

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;
    }
}
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:
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);
Or we can set the custom model for the combo box after it’s created like this:
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: 
    1
    2
    3
    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):
    1
    2
    3
    4
    5
    6
    7
    8
    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) : 
    1
    2
    3
    4
    5
    6
    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);
    Note that the addItem() method of the JComboBox class still works in case of using a custom model.
  • Removing items from the combo box (using the removeItem() or removeItemAt()methods): 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 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): 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 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): 
    1
    2
    3
    4
    5
    6
    7
    // 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): 
    1
    2
    // 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!");
        }
    }
});
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.

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:
1
2
bookList.setForeground(Color.BLUE);
bookList.setFont(new Font("Arial", Font.BOLD, 14));
And limit the maximum number of items displayed in the drop-down list:
1
bookList.setMaximumRowCount(5);
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.
Here’s the screenshot of a combo box whose appearance is customized as above:
A simple customized combo box

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:
Swing JComboBox Demo program
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:
Message dialog when click Select

Java JComboBox Example

  1. import javax.swing.*;    
  2. public class ComboBoxExample {    
  3. JFrame f;    
  4. ComboBoxExample(){    
  5.     f=new JFrame("ComboBox Example");    
  6.     String country[]={"India","Aus","U.S.A","England","Newzealand"};        
  7.     JComboBox cb=new JComboBox(country);    
  8.     cb.setBounds(5050,90,20);    
  9.     f.add(cb);        
  10.     f.setLayout(null);    
  11.     f.setSize(400,500);    
  12.     f.setVisible(true);         
  13. }    
  14. public static void main(String[] args) {    
  15.     new ComboBoxExample();         
  16. }    
  17. }   
Output:
JAVA Jcombobox 1

Java JComboBox Example with ActionListener

  1. import javax.swing.*;    
  2. import java.awt.event.*;    
  3. public class ComboBoxExample {    
  4. JFrame f;    
  5. ComboBoxExample(){    
  6.     f=new JFrame("ComboBox Example");   
  7.     final JLabel label = new JLabel();          
  8.     label.setHorizontalAlignment(JLabel.CENTER);  
  9.     label.setSize(400,100);  
  10.     JButton b=new JButton("Show");  
  11.     b.setBounds(200,100,75,20);  
  12.     String languages[]={"C","C++","C#","Java","PHP"};        
  13.     final JComboBox cb=new JComboBox(languages);    
  14.     cb.setBounds(50100,90,20);    
  15.     f.add(cb); f.add(label); f.add(b);    
  16.     f.setLayout(null);    
  17.     f.setSize(350,350);    
  18.     f.setVisible(true);       
  19.     b.addActionListener(new ActionListener() {  
  20.         public void actionPerformed(ActionEvent e) {       
  21. String data = "Programming language Selected: "   
  22.    + cb.getItemAt(cb.getSelectedIndex());  
  23. label.setText(data);  
  24. }  
  25. });           
  26. }    
  27. public static void main(String[] args) {    
  28.     new ComboBoxExample();         
  29. }    
  30. }    
Output:
JAVA Jcombobox 2
IN THE NEXT TUTORIAL, WE SHALL DISCUSS ON JCOMBOBOX WITH CUSTOM GUI

No comments:

Post a Comment

Facebook