gpt4 book ai didi

java - 如何在JTable中显示图片?

转载 作者:行者123 更新时间:2023-12-02 04:29:40 25 4
gpt4 key购买 nike

当我尝试在 JTable 的单元格内显示图像时,我遇到了一个小问题,它采用文本格式并显示图像本身。

E.G. icon.toString()”返回:

enter image description here

我的代码:

public void loading() {
try {
String[]title = {"First Name","Last Name","Picture"};

String sql="select * from users";
model = new DefaultTableModel(null,title);
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
String[]fila = new String[4];

while(rs.next()){
fila[0] = rs.getString("fna");
fila[1] = rs.getString("lna");
byte[] imgBytes = rs.getBytes("pic");
Blob blob = new javax.sql.rowset.serial.SerialBlob(imgBytes);
BufferedImage image = null;
try (InputStream is = blob.getBinaryStream()) {
image = ImageIO.read(is);
ImageIcon icon = new ImageIcon(image);
fila[2] = icon.toString();
} catch (IOException exp) {
exp.printStackTrace();
}
model.addRow(fila);
}
tbl.setModel(model);
}
catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

有人知道如何更正代码吗?

最佳答案

您需要重写 TableModel 中的 getColumnClass(int col) 方法,以便它为您想要显示 ImageIcon 的列返回 ImageIcon.class,并将 ImageIcon 直接分配给 fila[2]:

public void loading() {
try {
String[]title = {"First Name","Last Name","Picture"};
String sql="select * from users";
model = new DefaultTableModel(null,title){
@Override
public Class<?> getColumnClass(int column) {
if (column==2) return ImageIcon.class;
return Object.class;
}
}
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
Object[]fila = new Object[4];
while(rs.next()){
fila[0] = rs.getString("fna");
fila[1] = rs.getString("lna");
fila[2] = new ImageIcon(rs.getBytes("pic"));
model.addRow(fila);
}
tbl.setModel(model);
}
catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

关于java - 如何在JTable中显示图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com