Question

So I'm currently working on a GUI for a school project, where we are making a Hotel Management System. Currently my task is to populate a jTable with some objects from our SQL database.

I have read up on it and the easiest way seems to be to use the defaulttablemodel, but I'm not sure how to incorporate that into my already existing GUI.

That is what my jForm currently looks like, not sure if that helps anyone at all, but at least it's a visual of what I'm trying to do.

And this is my "RoomMapper"

public class RoomMapper {

public ArrayList<Room> getRooms(Connection con) {

    ArrayList<Room> rooms = new ArrayList();

    String sqlString1
            = "select * from room "
            + "order by room_id";
    String sqlString2 = "SELECT TABLE_NAME FROM USER_TABLES";

    PreparedStatement statement;
    try {

        statement = con.prepareStatement(sqlString1);
        ResultSet rs = statement.executeQuery();
        int i = 0;
        while (rs.next()) {
            i++;
            System.out.println(rs.getString(1));
            System.out.println("just added room nb " + i);
            rooms.add(new Room(rs.getInt(1), rs.getInt(2), 0, "stringy string"));
        }

        statement.close();
    } catch (Exception e) {
        System.out.println("Fail in RoomMapper - getRooms");
        System.out.println(e.getMessage());
    }
    System.out.println("rooms arraylist size: " + rooms.size());
    return rooms;
}
}
Was it helpful?

Solution

Create a tablemodel

DefaultTableModel model = new DefaultTableModel();

Create headers

String[] headers = {"1", "2"};

Set headers

model.setColumnIdentifiers(headers);

Populate the model

model.addRow(new Object[]{room.get1(), room.get2()});

Set tablemodel to the table

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top