Search code examples
javaswingjtablejscrollpanejtableheader

DefaultTableModel doesn't show columns


I have problem with DefaultTableModel it won't show me my columns in table, there is a part of code:

JTable table = new JTable() {
        public boolean isCellEditable(int data, int columnNames) {
            return false;
        }
    };
    String columnNames[] = new String[] { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian", "asd", "asd" };
    DefaultTableModel dtm = new DefaultTableModel(0, 0);
    dtm.setColumnIdentifiers(columnNames);

    table.setModel(dtm);
for (Reservation r : reservation) {
        rez.add(new Reservation(r.getID(), r.getA(),    r.getB(), r.getC(), r.getD(), r.getE(), r.getF()));

    }

    for (int i = 0; i < rez.size(); i++) {
        int id = rez.get(i).getID();
        String l = rez.get(i).getA();
        String w = rez.get(i).getB();
        String z = rez.get(i).getC();
        String o = rez.get(i).getD();
        String d = String.valueOf(rez.get(i).getE());
        String g = rez.get(i).getF();
        dtm.addRow(new Object[] { id, l, w, z, d,o,g });

    }


    JScrollPane sp = new JScrollPane(dtm);
    add(table);

}

Im trying to make a dynamic table. Data will be from data base (posgreSQL) using hibernate, and thats fine, it work's but I cant see a column names from

String columnNames[] = new String[] { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian", "asd", "asd" };

Don't care about names of columns and name of getters i changed it for this post.

In addition I can't make it scrollable:

JScrollPane sp = new JScrollPane(dtm);

Solution

  • I'm not sure how this would be able to compile

    JScrollPane sp = new JScrollPane(dtm);
    add(table);
    

    dtm is an instance of DefaultTableModel so it should never be possible to pass it to a JScrollPane,

    Instead you should be using

    JScrollPane sp = new JScrollPane(table);
    add(sp);
    

    See How to Use Tables and How to Use Scroll Panes for more details