如何恢复JTable中的列宽?

问题描述

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

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

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(..)

解决方法

您需要自己进行管理。

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

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...