我知道这是一个重复的问题,但我无法找到答案。我已成功使用数据库中的数据创建了JTable
。在我的JTable
中,其中一列保存图像。我试图用getColumnClass(int column)
显示这些图像,但我不明白如何使用此方法&没有好的教程我发现我能理解......我如何在我的JTable
中显示这些图像?
import java.sql.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BurgerData extends JFrame
{
JTable BurgerList;
public BurgerData()
{
setSize(800,800);
setLayout(new FlowLayout());
setVisible(true);
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/image","root","");
Statement stmnt = con.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * FROM `icon`");
ResultSetMetaData rsmetadata = rs.getMetaData();
int col = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector<String> col_name = new Vector<String>();
Vector<Object> row_data = new Vector<Object>();
for(int i=1;i<=col;i++)
{
col_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(col_name);
while(rs.next())
{
row_data = new Vector<Object>();
for(int i=1;i<=col;i++)
{
row_data.addElement(rs.getObject(i));
}
dtm.addRow(row_data);
}
BurgerList = new JTable( dtm )
{
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
BurgerList.setModel(dtm);
add(BurgerList);
}
catch(SQLException e)
{
System.out.println("Unknown Error");
}
catch(Exception eg)
{
System.out.println("Unknown Error");
}
}
public static void main(String args[])
{
BurgerData n = new BurgerData();
}
}
答案 0 :(得分:2)
I have already inserted Images
It is showing some string like : [B@6b4455f0] )
A JTable
does not have a default renderer for an Image
, so you are seeing the toString()
representation of the Image
.
Instead you need to create an ImageIcon
using the Image
. The JTable
will then use a JLabel to renderer the Icon
.
For example: How to set icon in a column of JTable?
进行PHPExcel下载工作row_data.addElement(rs.getObject(i));
因此,您无法将所有对象复制到表模型中。您需要检查Object是否为Image,然后创建ImageIcon并将其添加到模型中。
另一种解决方案是为Image类创建自定义渲染器(然后您可以直接将对象复制到模型中)。有关详细信息,请参阅Using Custom Renderers上Swing教程中的部分。