I have this program and I want to add a background image to my comboBox
. I have try many methods and i cant make it, so may someone help?
class myClass
{
public static void main(String args[])
{
JFrame myFrame = new JFrame();
myFrame.setBounds(500,500,500,500);
myFrame.setLayout(null);
myFrame.setVisible(true);
JComboBox myComboBox = new JComboBox();
myComboBox.setBounds(100,100,100,20);
myComboBox.add("item1");
myComboBox.add("item2");
myComboBox.setVisible(true);
Image comboBoxImage = new ImageIcon(
myClass.class.getResources("/Image.png")).getImage();
}
}
how to set the comboBoxImage
as background of the myComboBox
combobox?
You can set a custom renderer to you combo box using:
myComboBox.setRenderer(...);
A possible implementation of the renderer could be:
class BackgroundRenderer extends JLabel implements ListCellRenderer<String> {
private final Image image;
public BackgroundRenderer(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this);
super.paintComponent(g);
}
@Override
public Component getListCellRendererComponent(JList<? extends String> list, String value, int index,
boolean isSelected, boolean cellHasFocus) {
setText(value);
return this;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.