如何在 JLabel 上将图像路径转换为图像

How to convert image path into image on JLabel

当我select记录来自JTable时,我想给定路径的图像显示在JLabel中。当我写代码时:

private void profile_tableMouseClicked(java.awt.event.MouseEvent evt) {
    DefaultTableModel model = (DefaultTableModel) profile_table.getModel();
    dr_profile_image.setIcon((Icon)model.getValueAt(profile_table.getSelectedRow(),9));
}

我收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.Icon

抛出异常是因为您正在将 String 转换为 IconDefaultTableModel.getValueAt(int row, int col) returns row,col 中的项作为 Object 并且其 class 类型是存储在 table 模型中的实例的 class ,在你的例子中是 String。如果此值是您要使用的图像文件的路径,那么您将需要从该路径创建一个 Icon。您可以使用 javax.swing.ImageIcon 来执行此操作:

import javax.swing.ImageIcon;

private void profile_tableMouseClicked(java.awt.event.MouseEvent evt)
{
   DefaultTableModel model = (DefaultTableModel) profile_table.getModel();
   dr_profile_image.setIcon(
      new ImageIcon(model.getValueAt(profile_table.getSelectedRow(),9).toString());
}