Create a default JComboBox cannot display icons, indents, and so on on each entry. But Swing's MVC design architecture provides unmatched scalability for a variety of components. To do this, we can create a new renderer to take care of the drawing of each entry.
First we write a new class Imagedcomboboxitem, which encapsulates information about a Drop-down entry, including icons, text, indents, and so on:
class Imagedcomboboxitem {
private icon icon = null;
private String text = null;
private int indent = 0;
Imagedcomboboxitem (String Text, icon icon, int indent) {
this.text = text;
This.icon = icon;
this.indent = indent;
}
public String GetText () {
return text;
}
public Icon GetIcon () {
return icon;
}
public int getindent () {
return indent;
}
}
Then create a new Jimagedcombobox class and inherit from JComboBox. In the constructor, create a new defaultlistcellrenderer as the renderer and overwrite its Getlistcellrenderercomponent method. In the new Getlistcellrenderercomponent method, the parent object's method is still invoked first to complete the drawing of the normal entry, and then to determine if the entry is a Imagedcomboboxitem instance. If it does, it displays the Imagedcomboboxitem text, icon, and indents. To make it easier to display the left indent, we directly create a emptyborder and set the left indent quantity and set it to the Defaultlistcellrenderer. Defaultlistcellrenderer inherit from JLabel, so can directly accept all kinds of border. Here we take each indentation of 10 pixels as an example.
Well, here's the complete code:
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Jimagedcombobox extends JComboBox {
public Jimagedcombobox (Vector values) {
super (values);
listcellrenderer renderer = new Defaultlistcellrenderer () {
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.