You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JTable点击显示图片到JLabel报[B cannot be cast to ImageIcon错误如何解决

问题根源

你遇到的java.lang.ClassCastException: [B cannot be cast to javax.swing.ImageIcon错误中,[B是Java对字节数组byte[]类型的标识,说明你的prodtable表格第4列存储的不是ImageIcon对象,而是图片对应的二进制字节数组,直接把字节数组强转为ImageIcon就会抛出类型转换异常。

修复方案

你需要先把取到的字节数组转换成ImageIcon对象,再做后续的缩放、赋值给JLabel的操作,修改后的代码如下:

private void prodtableMouseClicked(java.awt.event.MouseEvent evt) {                                       
    DefaultTableModel model = (DefaultTableModel)prodtable.getModel();
    // 没有选中行直接返回,避免空指针
    int selectedViewRow = prodtable.getSelectedRow();
    if (selectedViewRow < 0) {
        return;
    }
    // 开启表格排序/过滤时需要把视图行索引转成模型行索引,避免取值错位
    int Myindex = prodtable.convertRowIndexToModel(selectedViewRow);
    prodcode.setText(model.getValueAt(Myindex, 0).toString());
    prodname.setText(model.getValueAt(Myindex, 1).toString());
    prodqty.setText(model.getValueAt(Myindex, 2).toString());
    prodprice.setText(model.getValueAt(Myindex, 3).toString());

    // 先取字节数组,再转ImageIcon
    byte[] imageBytes = (byte[]) model.getValueAt(Myindex,4);
    if (imageBytes == null || imageBytes.length == 0) {
        dimg.setIcon(null);
        return;
    }
    ImageIcon image1 = new ImageIcon(imageBytes);
    Image image2 = image1.getImage().getScaledInstance(dimg.getWidth(),dimg.getHeight(),Image.SCALE_SMOOTH);
    ImageIcon image3 = new ImageIcon(image2);
    dimg.setIcon(image3);
}

补充优化点

  • 新增了选中行判空、图片字节数组判空逻辑,避免无选中行、无图片数据时出现空指针异常
  • 新增视图索引转模型索引的逻辑,适配表格开启排序、过滤功能后的取值场景

内容的提问来源于stack exchange,提问作者Emmam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:24:00