我問here如何正確添加背景圖片的JComboBox,但沒有看到答案,所以我想,我應該對這兩個問題分開......如何將背景圖像添加到JComboBox?
所以。如何將JComboBox文本字段和JComboBox彈出式面板的背景圖像正確添加?
UPD: 一些對你的代碼)
當前代碼:
// ... Renderer
public class CBoxListCellRenderer implements ListCellRenderer {
ImagePanel panel;
JLabel label = new JLabel();
public CBoxListCellRenderer(Image img) {panel = new ImagePanel(img);}
public void setImage(Image img) {panel.setImage(img);}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
label.setText(value.toString());
panel.add(label);
return panel;
}
}
// ... ImagePanel
public class ImagePanel extends JPanel {
private BufferedImage img;
public ImagePanel(String img) {
setImage(img);
}
public void setImage(String img)
{
try {
this.img = ImageIO.read(this.getClass().getResource(img));
} catch (IOException ex) {
ex.printStackTrace();
}
Dimension size = new Dimension(this.img.getWidth(), this.img.getHeight());
setSize(size);
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), 0, 0, img.getWidth(), img.getHeight(), this);
}
}
// ... Colorizing arrow
class ColorArrowUI extends BasicComboBoxUI {
public static ComboBoxUI createUI(JComponent c) {
return new ColorArrowUI();
}
@Override protected JButton createArrowButton() {
return new BasicArrowButton(
BasicArrowButton.SOUTH,
Color.cyan, Color.magenta,
Color.yellow, Color.blue);
}
}
// ... Creating object
combo_language = new JComboBox(new DefaultComboBoxModel(new String[] { "English", "日本語", "Русский" }));
combo_language.setBorder(null);
combo_language.setRenderer(new CBoxListCellRenderer(new ImageIcon(getClass().getResource("/Images/form.png")).getImage()));
combo_language.setUI(new ColorArrowUI());
// ... Putting JComboBox to JFrame
但未看到答案,請查看incl。合理的代碼,也適用於JComboBox – mKorbel
@mKorbel接受的答案或...? – RussianVodka
是的,但是您必須爲JComponents使用不透明度,默認情況下每個setOpaque都可以透明 – mKorbel