JTable中某个单元格如何添加一张图片,具体一点的步骤,最好有举例代码 50
展开全部
写一个定制的 TableCellRenderer 类 :
import java.awt.Component;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
// 应用到所有的单元格:
// table.setDefaultRenderer(Object.class, new ImageRenderer());
// 或者,应用到某一列的单元格:
// table.getColumnModel().getColumn((int)columnIndex).setCellRenderer(new ImageRenderer());
public class ImageRenderer implements TableCellRenderer
{
@SuppressWarnings("unchecked")
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int rowIndex, int columnIndex) {
if( value instanceof Image )
return new JLabel(new ImageIcon((Image)value));
else if( value instanceof File ) {
try {
return new JLabel(new ImageIcon(ImageIO.read((File)value)));
} catch(IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
else {
String val = String.valueOf(value);
try {
return new JLabel(new ImageIcon(ImageIO.read(new File(val))));
} catch(IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
}
}
import java.awt.Component;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
// 应用到所有的单元格:
// table.setDefaultRenderer(Object.class, new ImageRenderer());
// 或者,应用到某一列的单元格:
// table.getColumnModel().getColumn((int)columnIndex).setCellRenderer(new ImageRenderer());
public class ImageRenderer implements TableCellRenderer
{
@SuppressWarnings("unchecked")
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int rowIndex, int columnIndex) {
if( value instanceof Image )
return new JLabel(new ImageIcon((Image)value));
else if( value instanceof File ) {
try {
return new JLabel(new ImageIcon(ImageIO.read((File)value)));
} catch(IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
else {
String val = String.valueOf(value);
try {
return new JLabel(new ImageIcon(ImageIO.read(new File(val))));
} catch(IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
}
}
追问
能给个举例代码么,急啊,比如我要让table的第3列都能显示图片,并让第3列的第4个单元格显示出图片(路径是D:\\123.jpg)谢谢
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询