Jcombobox渲染实例

来源:互联网 发布:笑脸雾化器口感数据 编辑:程序博客网 时间:2024/06/13 08:21

首先写个渲染类:

 

package goodutils.framworks;

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

import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class JcomboboxListcellRender implements ListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {
        if(value instanceof JPanel){
            if(isSelected){
                ((JPanel)value).setBackground(Color.LIGHT_GRAY);
            }else {
                ((JPanel)value).setBackground(Color.white);
            }
            return (JPanel)value;
        }
        return null;
    }

}

 

然后写个jpanel类:主要的目的是封装jcombox中的对象;便于管理

package goodutils.framworks;

import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
//下拉框中的对象
public class JComboboxItemJpanel extends JPanel {
   
    private JLabel statuName;
    private JLabel stateIcon;

    public JComboboxItemJpanel(String statuname,String imagepath) {
      setLayout(new FlowLayout());
      statuName=new JLabel(statuname);
      stateIcon=new JLabel();
      stateIcon.setIcon(getImageIcon(imagepath));
      add(getStatuName());
      add(getStateIcon());
    }
    //导入图片
    public ImageIcon getImageIcon(String imagepath){
        ImageIcon image= new ImageIcon(getClass().getResource(imagepath));
        return image;
    }
    public JLabel getStatuName() {
        if(statuName==null){
            statuName=new JLabel("状态");
        }
        return statuName;
    }

    public void setStatuName(JLabel statuName) {
        this.statuName = statuName;
    }

    public JLabel getStateIcon() {
        if(stateIcon==null){
            stateIcon=new JLabel("图标");
        }
        return stateIcon;
    }

    public void setStateIcon(JLabel stateIcon) {
        this.stateIcon = stateIcon;
    }
   
}
调用的时候写法如下:


        comboBox_status = new JComboBox(new JPanel[]{
                new JComboboxItemJpanel("在线","/image/logo.gif"),
                new JComboboxItemJpanel("隐身","/image/logo.gif"),
                new JComboboxItemJpanel("离开","/image/logo.gif"),
                new JComboboxItemJpanel("忙碌","/image/logo.gif")
        });
        comboBox_status.setPreferredSize(new Dimension(60, 30));
        comboBox_status.setRenderer(new JcomboboxListcellRender());
        panel_5.add(comboBox_status);

注意红色的部分必须加上,这句话的目的是给jcombobox添加渲染器,如果不加的话,对象打印的是他的tostring方法:

 

原创粉丝点击