Question

I'm trying to create a JTable with the column headers defined in colName using a DefaultTableModel, then adding the table to a JScrollPane then to a JPanel. However, when I add the panel to my JFrame, only the panel shows up, not the table. I am using similar code in another table, and that one shows up fine, only difference being the number of columns and variable names.

What am I missing?

My code :

    //Column Names
    final String[] colNames = {"Item", "Count"};
    DefaultTableModel dtm = new DefaultTableModel(0, colNames.length);

    //Panel to hold Table
    JPanel j = new JPanel(new BorderLayout());
    j.setBounds(9, 78, 267, 254);

    //Colored to see if the panel has been added
    j.setBackground(Color.RED);

    //Set Column Headers
    dtm.setColumnIdentifiers(colNames);

    //Jtable with model
    JTable t = new JTable(dtm);
    t.setBackground(Color.GREEN);

    t.getTableHeader().setReorderingAllowed(false);
    t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

    t.getColumnModel().getColumn(0).setPreferredWidth(113); 
    t.doLayout();

    j.add(new JScrollPane(t), BorderLayout.CENTER);
Was it helpful?

Solution

I would suggest that the column's are being overridden by those reported back by the table model. You could instead use...

String[] colNames = {"Item", "Count"};
DefaultTableModel dtm = new DefaultTableModel(colNames, 0);

JPanel j = new JPanel(new BorderLayout());

JTable t = new JTable(dtm);
t.setBackground(Color.GREEN);

t.getTableHeader().setReorderingAllowed(false);
t.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

t.getColumnModel().getColumn(0).setPreferredWidth(113); 

j.add(new JScrollPane(t), BorderLayout.CENTER);

Instead...

Without seeing the code you're using to put the table on the frame, it's difficult to comment further, however...

  • Avoid using setBounds, it's pointless in this context any way.
  • The background color will actually be defined more by the view port then the table or panel until the table is either configured to fill the empty space or has enough rows to fill the empty space
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top