Home > Net >  Java JTableModel to display horizontally
Java JTableModel to display horizontally

Time:12-07

I have a resultset from a query (date and room) some kind of matrix.

9 room and date between (jan/01/2022 to jan/31/2022).

try {
    String query="select  a.Tarikh AS 'TARIKH',a.Room AS 'ROOM',b.Room as 'BOOKED'"
              "from     (Select * from Tarikh Cross Join Room) as a\n"
              "left join Booking as b\n"
              "on        a.Tarikh = b.Tarikh\n"
              "and       (a.Room = b.Room)\n"
              "WHERE        (a.Tarikh BETWEEN '2022-01-01' AND '2022-03-01');";
    PreparedStatement pst=connection.prepareStatement(query);
    ResultSet rs = pst.executeQuery();

    // this line below implement the usage of net.proteanit.sql.DbUtils (import library)    
    table_1.setModel(DbUtils.resultSetToTableModel(rs));
    // ---      

    pst.execute();  
    rs.close();
} catch (Exception e) {
    e.printStackT
}
            

The problem is, how do I make a JtableModel to display from this

Room    Date            Booked
101 2022-01-01  2022-01-01
102 2022-01-01  2022-01-01
103 2022-01-01  2022-01-01
104 2022-01-01  2022-01-01
105 2022-01-01  null
106 2022-01-01  null
107 2022-01-01  null
108 2022-01-01  null
109 2022-01-01  null
101 2022-01-02  null
102 2022-01-02  2022-01-02
103 2022-01-02  null
104 2022-01-02  null
105 2022-01-02  null
106 2022-01-02  null
107 2022-01-02  null
108 2022-01-02  null
109 2022-01-02  null
and so on....

enter image description here

I am expecting the records to be :

       0101  0201 0301 0401 0501 and so on....
101      X 
102      X     X
103      X 
104      X
105
106
107
108
109

Does anyone know, please help.TQ

CodePudding user response:

You need to parse the ResultSet data to create your TableModel manually.

I might start by creating a TreeMap from the ResultSet data. The room number is the key and an ArrayList can be use each non-null booked date.

Once this is done you can then create a DefaultTableModel with "x" rows and 32 columns. The number of rows will be based on the number of entries in the TreeMap. The first column will be the room number. The next 31 columns will be the days of the month.

Now you need to read each key from the TreeMap. Each key will represent a row in the TableModel. As you read each key:

  1. set the room number in the first column: setValueAt(roomNumber, currentRow, 0)
  2. loop thru each booked date in the ArrayList and parse out the day. So "2022-01-01" will become column 1. Now you can update the value in your model using setValueAt("X", currentRow, column)
  3. increment the currentRow

Repeat the above steps for all keys in the TreeMap.

  • Related