JTable 设置模型并保留列格式(宽度、对齐方式等) [英] JTable setting model and preserve column formats (width, alignment, etc.)

查看:39
本文介绍了JTable 设置模型并保留列格式(宽度、对齐方式等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个JTable绑定的脑洞体验.这就是我所做的.我创建了一个 JTable,其中的列设置为指定的宽度,使用 renderers 对其进行格式化,并在其上添加了一些代码.但是当我尝试将其绑定到模型时,所有列都被模型的字段替换.有没有办法正确绑定?

This is a brain-cracking experience with JTable binding. Here's what I did. I created a JTable with columns set to a specified width, formatted it using renderers, and added some codes on it. But when i try to bind it to a model, all the columns were replaced by the fields of the model. Is there a way on how to correctly bind it?

我正在避免循环,因为数据库中有 100 多条记录.我正在尝试使用其他方法,例如 BeansBindingEntityManager 但我不知道如何更改数据源(这就是我选择将其绑定到模型),因为我正在测试它以备份数据库,并很快将实施到新服务器.

I'm avoiding loops because there are 100+ thousand records in the database. I'm trying to use other methods such as BeansBinding and EntityManager but I don't know how to change the datasource (that's why i choose binding it to a model) because I'm testing this to backup database and soon to be implemented to the new server.

这是我在 .Net 中所做的,我通常创建一个 datagridview 并将其绑定到一个数据集,它工作正常.但我不能将它应用于java.我需要你的意见,我如何在可以处理 100+ 千条记录的 Java 中做到这一点.

This is what I did in .Net, I usually create a datagridview and binded it to a dataset and it works fine. But i cannot apply it to java. I need your opinion on how can I do it in java that can handle 100+ thousand records.

    PreparedStatement pst = conn.prepareStatement("SQL Query here");
    ResultSet rs = pst.ExecuteQuery();
    jTable1.setModel(DbUtils.resultSetToTableModel(rs));

上面的代码工作正常,但我对此非常非常大的问题是它用模型中的列覆盖了我的格式化列.

The code above works fine but my very very big problem on this is that it overrides my formatted columns by the columns in the model.

请帮我解决这个问题.

推荐答案

根据评论,您可以尝试在 DbUtils 中添加以下方法:

Based on the comments, you could try to add the following method to DbUtils:

public static void updateTableModelData(DefaultTableModel tModel, ResultSet rs) 
        throws Exception {
    tModel.setRowCount(0);
    ResultSetMetaData metaData = rs.getMetaData();

    while (rs.next()) {
        Vector newRow = new Vector();
        for (int i = 1; i <= numberOfColumns; i++) {
            newRow.addElement(rs.getObject(i));
        }
        tModel.addRow(newRow);
    }
}

然后你的代码会变成:

PreparedStatement pst = conn.prepareStatement("SQL Query here");
ResultSet rs = pst.ExecuteQuery();
DbUtils.updateTableModelData((DefaultTableModel) jTable1.getModel(), rs);

这篇关于JTable 设置模型并保留列格式(宽度、对齐方式等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆