[英]adding background image to JComboBox
I have this program and I want to add a background image to my comboBox
. 我有这个程序,我想向我的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? 如何将comboBoxImage
设置为myComboBox
组合框的背景?
You can set a custom renderer to you combo box using: 您可以使用以下方法在组合框中设置自定义渲染器:
myComboBox.setRenderer(...); 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.