Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify JTable to fit screen

I have created an app just for exercise purpose with a JTable in it to show the data coming from my database.

My problem is that the table shows up in half the panel on my screen. I've tried everything to expand the columns without success. Can someone tell me how to modify the table?

Here is the code that creates the table:

    public void createTable() {
    JTable table = new JTable();
    DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},new String[]{"To do","Date added"});
    table.setSize(450, 600);
    table.setModel(tableModel);
    for(int i = 0; i < model.getId().size(); i++) {
        tableModel.addRow(new Object[]{model.getItem().get(i), model.getDate().get(i)});
    }
    add(table.getTableHeader());
    add(table);
}

Here is how it looks right now:

enter image description here

Also I want to ask about table.getTableHeader() because if I don't add that it doesn't show up since it is a part of the table.. is that normal?

like image 903
Reshad Avatar asked Dec 05 '25 14:12

Reshad


1 Answers

  • JPanel has FlowLayout implemented in API, then your JPanel layed JComponents correctly, with yours logics (add JTableHeader, add JTable)

  • change that to the BorderLayout and to put JTableHeader to the NORTH / SOUTH and JTable to the CENTER

  • use JScrollPane for JTables view, everything else is bothering with LayoutManager and calculating for PreferredSize very ugly way,

like image 90
mKorbel Avatar answered Dec 07 '25 03:12

mKorbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!