如何在JTable中恢复列宽? [英] How to restore column widths in a JTable?

查看:113
本文介绍了如何在JTable中恢复列宽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很明确.用户调整大小后,是否可以自动恢复列的宽度?

My question is clear. Is there any way to restore the width of the columns automatically after user has resized them?

每次单击按钮时,我都希望恢复列宽.

Every time the button is clicked, I want the column widths to be restored.

public class TableTest {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());

            JTable table = new JTable(new Object[][] { { "something", "something else" } },
                    new Object[] { "Col1", "Col2" });
            table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                            column);
                    label.setForeground(Color.GREEN);
                    return label;
                }
            });
            frame.add(new JScrollPane(table), BorderLayout.CENTER);

            JButton button = new JButton("Button");
            button.addActionListener(e -> {
                // Restore column widths here
            });
            frame.add(button, BorderLayout.PAGE_END);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }
}

我尝试过:

table.setAutoCreateColumnsFromModel(false);
table.setAutoCreateColumnsFromModel(true);

但是它将删除渲染器.

我尝试过:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

但是什么也没做.

我尝试过:

for (int col = 0; col < table.getColumnCount(); col++) {
    table.getColumnModel().getColumn(col).sizeWidthToFit();
}

机器人什么也不做.

有办法吗?还是我必须自己计算然后getColumnModel.getColumn(..).setPreferredWidth(..)?

Is there a way? Or I have to calculate it myself and then getColumnModel.getColumn(..).setPreferredWidth(..) ?

推荐答案

您需要自己进行管理.

默认情况下,宽度设置为75,因此您只需将宽度重置为75.

By default the width is set to 75, so you can just reset the width to 75.

或者您可以在GUI可见后始终查询列的宽度.然后根据此值恢复宽度.

Or you can always query the width of the column after the GUI is visible. Then restore the width based on this value.

没有默认功能以原始宽度显示列

There is no default functionality to display the column at its original width

这篇关于如何在JTable中恢复列宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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