Search code examples
javaswingjtabletablecellrendererjtableheader

Real Time jTable column resizing


I am working on a project where I add the column names from mysql into jTable. I want that when a name is added, the column should adjust its size according to the length of column name. I will make myself clearer, but first heres the existing code:

jTextArea1.setText(null);
tableModel.setColumnCount(0);
colwidth = 0;
try {
    Class.forName("java.sql.DriverManager");
    con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/" + (String) jList1.getSelectedValue(), "" + GlobalParams.uservar, "" + GlobalParams.passvar);
    Statement stmnt = (Statement) con.createStatement();
    String query1 = "Use " + GlobalParams.dbvar;
    stmnt.executeQuery(query1);
    String query2 = "desc " + (String) jList2.getSelectedValue();
    ResultSet rs = stmnt.executeQuery(query2);
    while (rs.next()) {
        fieldo = rs.getString("Field");
        jTextArea1.append(fieldo + "\n");
    }
    Scanner scanner = new Scanner(jTextArea1.getText());
    timeget();
    jTextArea4.append(now + ":   " + "/ Scanning Available feeds from table '" + (String) jList2.getSelectedValue() + "' / \n");
    timeget();
    jTextArea4.append(now + ":   " + "/ Getting feeds from table '" + (String) jList2.getSelectedValue() + "' / \n \n");
    if (scanner.hasNextLine()) {
        scanner.nextLine();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            tableModel.addColumn(line);
            jTable1.getColumnModel().getColumn(colwidth).setWidth(line.length());
            colwidth++;
            int end = jTextArea1.getLineEndOffset(0);
            jTextArea1.replaceRange("", 0, end);
        }
    }
} catch (Exception e) {
    JOptionPane.showMessageDialog(this, e.getMessage());
}

"colwidth" is a public static int and "fieldo" is a public static String.

What i want is, for ex.-> the string to be made into column is "asdadsasd123". I want that the column should adjust its width according to length of this string. I have set the auto resize of table to off. The table is enclosed in a scollpane. The layout of frame is Free Design.

I also did find the thread here-> Auto resizing the JTable column widths but i cant seem to understand this code:

    TableCellRenderer renderer = table.getCellRenderer(row, column);
    Component comp = table.prepareRenderer(renderer, row, column);
    width = Math.max(comp.getPreferredSize().width, width);

(Yeah, I aint very experienced with java). And I also dont want to do anything with rows for now, just resize the columns.

Here is screenshot of Default-> enter image description here

Here is how I want it to be-> enter image description here

Please help,thanks.


Solution

  • You can use the Table Column Adjuster.

    It will adjust the column width based on the size of the header the cell data or both.