Search code examples
javaswingjtablejtableheader

JTable Swing: I cannot resize column by dragging cursor in header


I cannot resize the column width by moving the cursor between header columns and drag the divider, despite of that I have set setResizingAllowed() to true.

tbResumen = new JTable();
tbResumen.setEnabled(false);

tbResumen.setRowHeight(20);
tbResumen.setBackground(UIManager.getColor("Table.selectionBackground"));
tbResumen.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tbResumen.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
tbResumen.setFont(new Font("Arial", Font.PLAIN, 12));
tbResumen.setDefaultRenderer(Object.class, new RenderTablaInfo());
tbResumen.setOpaque(false);

tbResumen.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tbResumen.setColumnSelectionAllowed(false);
tbResumen.setRowSelectionAllowed(true);

tbResumen.setSize(new Dimension(840, 450));
tbResumen.setPreferredScrollableViewportSize(new Dimension(840, 450));

tbResumen.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

tbResumen.setModel(new DefaultTableModel(new Object[][] {{ label1, label2, label3, label4} },
new String[] { "foo", "bar", "foobar", "barfoo" }));

final JTableHeader headerResumen = new JTableHeader();
headerResumen.setReorderingAllowed(false); 
headerResumen.setResizingAllowed(true);
headerResumen.setColumnModel(tbResumen.getColumnModel());

headerResumen.setTable(tbResumen);
tbResumen.setTableHeader(headerResumen);

If someone needs more code to clarify the situation I'll add them soon. Thanks.


Solution

    1. Make sure your header is the one you are about to configure.

    So, with:

    JTableHeader headerResumen = tbResumen.getTableHeader();
    headerResumen.setResizingAllowed(true);
    

    I just create another header with the same model of my table and do config there, not realizing that the new header I created is not that of my table. I must call table.getTableHeader() to get the header I want and the config can work. Sorry for the stupidity.

    1. Make sure you have set the cursor to be default cursor when hovering onto the edges between the columns in this table, so you can see it becomes a two-headed arrow and you are aware of that they are adjustable.

      tbResumen.setCursor(Cursor.getPredefinedCursor(CURSOR_DEFAULT));

    If you set it to CURSOR_HAND, no two-way cursor will not be shown.

    1. autoResizingMode can also trigger "problems", making it harder to adjust width. When it's set OFF, when you drag column edge, it may be moved, but not freely. Be sure to set the autoResizingMode to JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS or JTable.AUTO_RESIZE_NEXT_COLUMN to see considerable changes.

    2. (half a year later when I come back to my answer, I still find it useful...) If you disable the JScrollPane containing the table, the cursor will not change neither, and not two-way cursor will be shown.