0
votes

I'm encountering a problem about resizing the column based on the cell that has the longest content. In the following example, I want all cell's width re-adjust according to the length of the content in "ADDRESS" column. Please help, and thank you in advance.

    public void setPnLTable(int x, int y){

    String[] ColNames  = {"Name", "AGE", "ADDRESS"};
    private String [][] getData(){t[0][0] = "John Smith"; t[0][1] = "55"; t[0][2] = "1600 Pennsylvania Ave NW, Washington, DC 20500";

    DefaultTableModel  tm = new DefaultTableModel(getData(),ColNames);

    //
    jPnLTABLE        = new JTable(tm);

    //  Center Columns
    cr.setHorizontalAlignment( JLabel.CENTER );

    for (int i = 0; i < ColNames.length; i++){

        jPnLTABLE.getColumnModel().getColumn(i).setCellRenderer(cr);
    }

    jPnLTABLE.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

    JScrollPane js   = new JScrollPane(jPnLTABLE);

    //

    js.setBounds(x, y, 2000, 500); // IT'S HARD-CODED; 
                                  //CAN I RESIZE IT BASED ON THE LENGTH OF THE CELL CONTENT 

    jPnLTABLE.getTableHeader().setReorderingAllowed(false);
    jPnLTABLE.getTableHeader().setFont(new Font(null, Font.BOLD, 12));
    add(js);

}
1

1 Answers

0
votes

If you make your JFrame a BorderLayout and put your JScrollPane BorderLayout.CENTER no need at all to set the size of the JSrollPane it will take all the available space

If your JScrollPane is inside a cell of a GridLayout no problem neither it will re-ajust no need to set its size

Allways easier to put the JScrollPane inside a JPanel (GridLayout(1,1) or BorderLayout.CENTER) and let the Layout manager to do the adjustement on the JPanel.

or maybe you can use

table.setFillsViewportHeight( true );