How to restore column widths in a JTable?

天大地大妈咪最大 提交于 2021-01-29 00:35:48

问题


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);
        });
    }
}

I tried:

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

But it removes the renderer.

I tried:

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

But does nothing.

I tried:

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

Bot does nothing.

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


回答1:


You need to manage this yourself.

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

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



来源:https://stackoverflow.com/questions/63346826/how-to-restore-column-widths-in-a-jtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!