简体   繁体   English

如何将MySQL数据库中的图像显示到java中的jTable中?

[英]how to display image from database in MySQL into jTable in java?

In a project I am working on I have showStudents.java that enables me to view all the students in the database in a jTable swing component.在我正在处理的一个项目中,我有 showStudents.java,它使我能够在 jTable swing 组件中查看数据库中的所有学生。 The jTable is correctly displayed except that the image is showing as jTable 正确显示,除了图像显示为

    5   Debebe  Gemesa  2020-02-07  Adama       AB  0956852145  1   [B@522d8811
    6   Samuel  Gemeda  2020-02-05  Bahir Dar   A+  0986451278  1   [B@3330a9d5

The last column is supposed to be image column.最后一列应该是图像列。 In the database I have the following values for students table在数据库中,我有学生表的以下值

6 Samuel Gemeda 2020-02-05 Bahir Dar A+ 0986451278 1 [BLOB - 32 B]

I have this method in my showStudents.java that enables me to view all the columns from my database.我在我的 showStudents.java 中有这个方法,它使我能够查看我的数据库中的所有列。

public void showRecord(){
    try {
        stmt = conn.createStatement();
        String sql = "SELECT * FROM STUDENT";
        ResultSet rs = stmt.executeQuery(sql);
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

If you want to use DbUtils, then you will need to use a custom renderer to display the data.如果要使用 DbUtils,则需要使用自定义渲染器来显示数据。 That is you will need to convert the Blob to an ImageIcon and add the Icon to a JLabel .也就是说,您需要将Blob转换为ImageIcon并将Icon添加到JLabel This conversion would be done every time the cell of the table is rendered which is not very efficient.每次渲染表格的单元格时都会进行这种转换,这不是很有效。

Read the section from the Swing tutorial on How to Use Renderers for more information and working examples to get you started.阅读 Swing 教程中关于如何使用渲染器的部分,了解更多信息和工作示例以帮助您入门。

Or the other approach is to NOT use DbUtils.或者另一种方法是不使用 DbUtils。 Instead you read the data from the database into the DefaultTableModel yourself.相反,您自己将数据库中的数据读入DefaultTableModel The advantage of this approach is that you create the ImageIcon once, when the data is loaded, then you use the default Icon renderer of the JTable to display the Icon.这种方法的优点是你创建了ImageIcon一次,当数据加载时,然后你使用JTable的默认 Icon 渲染器来显示 Icon。

See: How to get a DefaultTableModel object's data into a subclass of DefaultTableModel for an example of reading the data directly into the table model.有关将数据直接读入表模型的示例,请参阅: 如何将 DefaultTableModel 对象的数据放入 DefaultTableModel 的子类中

You would need to modify the code to convert the Blob to an ImageIcon for your last column.您需要修改代码以将 Blob 转换为最后一列的ImageIcon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM