最近在做一个程序,要用到类似于vc中的CListCtrl控件功能,和QQ好友列表的那种图标一样,选定图标后会变蓝,API看了很久都没有发现比较有用的信息,只看到一个JLabel和那个比较相似,但是JLabel直接加到JList里面的话会出现不能选定,也就是选定后不变蓝的情况,而后在网络上得到的信息实现ListCellRenderer接口,然后对选定的JLabel设定背景颜色,而为了实现绘制JLabel的背景颜色,你不得不重写一个类继承JLabel并且重写paintComponent方法进行背景颜色的绘制,
效果图如下:
具体实现如下:
第一个类:继承Jlabel重写paintComponent方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics;
import javax.swing.Icon; import javax.swing.JLabel;
@SuppressWarnings("serial") public class JLabelView extends JLabel {
@Override
protected void paintComponent(Graphics g) {
FontMetrics fontMetrics = g.getFontMetrics(this.getFont()); int stringWidth = fontMetrics.stringWidth(this.getText());
int x,y,width,heigth;
Icon icon = getIcon();
y = 0; width = stringWidth+10;
if(icon==null) { x = 0; heigth = fontMetrics.getHeight();
}else { x = icon.getIconWidth(); heigth = icon.getIconHeight(); }
Color oldColor = g.getColor(); g.setColor(getBackground());
g.fillRect(x, y, width, heigth);
g.setColor(oldColor); super.paintComponent(g); }
public JLabelView() { super(); }
public JLabelView(Icon image, int horizontalAlignment) { super(image, horizontalAlignment); }
public JLabelView(Icon image) { super(image); }
public JLabelView(String text, Icon icon, int horizontalAlignment) { super(text, icon, horizontalAlignment); }
public JLabelView(String text, int horizontalAlignment) { super(text, horizontalAlignment); }
public JLabelView(String text) { super(text); }
}
|
第二个类:实现ListCellRenderer 接口,对选定的对象进行背景色的设定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer;
public class JLabelViewRender implements ListCellRenderer {
@Override public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean cellHasFocus) {
JLabel iconLabel = (JLabel)value;
if(isSelected) iconLabel.setBackground(new Color(889580)); else iconLabel.setBackground(Color.white);
return iconLabel; } }
|
测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class Test extends JFrame { private JList jList;
public Test() {
JLabelView jLabelView [] = new JLabelView[10];
for(int i=0;i<10;i++) { jLabelView[i] = new JLabelView("用户"+i, new ImageIcon("res/01.jpg"), JLabelView.LEFT); }
jList = new JList(jLabelView);
jList.setCellRenderer(new JLabelViewRender());
add(jList);
setSize(250, 600); setVisible(true); }
public static void main(String[] args) { new Test(); } }
|