public class mousergister extends JPanel {JPanel jp;JComboBox setImg;ComboBoxRenderer renderer;public static void main(String[] args) {
new mousergister();
}
public mousergister() {
BaseFrame bf=new BaseFrame("用户注册");
bf.add(this);
this.setLayout(null);
renderer = new ComboBoxRenderer();
renderer.setPreferredSize(new Dimension(100, 50));
Object elements[][] = {
{ new MyIcon("images/1.jpg",this)},
{ new MyIcon("images/2.gif",this) },
{ new MyIcon("images/3.jpg",this)},
};
setImg = new JComboBox(elements);
setImg.setRenderer(renderer);
setImg.setBounds(120, 25, 75, 60);
add(setImg);
bf.setLocation(500, 100);// 设置窗口在屏幕的位置
bf.setSize(320, 420);
bf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bf.setResizable(false);// 设置游戏窗口大小不可改变
bf.setVisible(true);
}
private class ComboBoxRenderer extends JLabel implements ListCellRenderer {
// 这样要是实现接口的方法:
/*
*
* This method finds the image and text corresponding to the selected
*
* value and returns the label, set up to display the text and image.
*/
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
ImageIcon image=null;
if (value instanceof Object[]) {
Object[] values = (Object[]) value;
image = (ImageIcon)values[0];
}
if (image != null) {
this.setIcon(image);
}
return this;
}
}
private class MyIcon extends ImageIcon{
private Image m;
private String str;
private mousergister jp;
public MyIcon(String str,mousergister jp) {
Toolkit tool;
tool = jp.renderer.getToolkit();
m = tool.getImage(str);
}
public void paintIcon(Component lab, Graphics g){
lab=jp.renderer;图片不会显示。。。怎么改?
2 回答
幕布斯1329279
TA贡献8条经验 获得超0个赞
getListCellRendererComponent()方法是需要修改的。
参数value是Object类型,if的判断条件value instanceof Object[]不会成立,if代码块是不会执行的。
if (value instanceof Object[]) {
Object[] values = (Object[]) value;
image = (ImageIcon)values[0];
}
if (image != null) {
this.setIcon(image); } return this; }
改成下面的试试。
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) { setIcon(new ImageIcon("images/1.jpg")); } if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } return this; }
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
Object elements[][] = { { new MyIcon("images/1.jpg",this)}, { new MyIcon("images/2.gif",this) }, { new MyIcon("images/3.jpg",this)}, };
这段直接用ImageIcon
Object elements[][] = { { new ImageIcon(this.getClass().getResource("images/1.jpg"))}, { new ImageIcon(this.getClass().getResource("images/2.gif")) }, { new ImageIcon(this.getClass().getResource("images/3.jpg"))}, };
添加回答
举报
0/150
提交
取消