Jcombobox渲染实例

首先写个渲染类:

 

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方法:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值