JAVA GUI 中下拉列表框中怎么添加图片

JAVA GUI 下拉列表框中怎么添加图片(每个选项前面都有图片, 就想QQ选择上线那样的) 还有单击时间
跪求高手

利用 渲染器:

JComboBoxTest 类:

package other;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;

import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class JComboBoxTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7864758081252556102L;

JComboBox jcb = null;

Toolkit kit = null;

DefaultComboBoxModel model = null;

File f = null;

public JComboBoxTest() {
this.setLayout(null);
kit = Toolkit.getDefaultToolkit();

jcb = new JComboBox();

model = new DefaultComboBoxModel();

Icon icon = new ImageIcon("d:/images/f5.jpg");//图片的路径 自己找个图片试一下就看到了
IconListItem iii = new IconListItem(icon, "下拉列表", "2103545");//列表中的每个元素

model.addElement(iii);

jcb.setModel(model);

NewCellRenderer ncr = new NewCellRenderer();
jcb.setRenderer(ncr);
jcb.setBounds(5, 50, 200, 70);

add(jcb);

setTitle("[userInfo]登陆中");
setLocation(kit.getScreenSize().width / 10 * 8,kit.getScreenSize().height / 7);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(220, 600));
setResizable(false);
setVisible(true);
}
public static void main(String args[]) {
new JComboBoxTest();
}
}

NewCellRenderer 类:

package other;

import java.awt.Color;
import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;

public class NewCellRenderer extends JLabel implements ListCellRenderer {
/**
*
*/
private static final long serialVersionUID = -4013237755398900553L;

private Border selectedBorder = BorderFactory.createLineBorder(Color.blue,1),emptyBorder =
BorderFactory.createEmptyBorder(1,1,1,1);
public NewCellRenderer(){
setOpaque(true);
}
public Component getListCellRendererComponent(JList listt, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
IconListItem listItem = (IconListItem) value; //value就是IconListItem类的实例
this.setIconTextGap(15);
this.setIcon(listItem.getIcon());
this.setText(listItem.getText()+" "+listItem.getUserID());
this.setHorizontalAlignment(JLabel.LEFT);
this.setSize(120, 27);

if (isSelected) {
setBorder(selectedBorder);
} else {
setBorder(emptyBorder);
}
return this;
}
}

IconListItem 类:

package other;

import javax.swing.*;

public class IconListItem {
Icon icon;//图片

String text;//文字

String userID;//ID等等

public IconListItem(Icon icon, String text, String userID) {
this.icon = icon;
this.text = text;
this.userID = userID;
}
public Icon getIcon() {
return icon;
}
public String getText() {
return text;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public void setText(String text) {
this.text = text;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}

这样基本就完成了。其余自己写希望对你有帮助。
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答