0

Many thanks for your help. :) I am trying to add a checkbox column into a JTable connected to a database. However, I think I am missing something because the funny thing is that both things work (The checkbox and the data extraction from the database), but not when they are together! Please let me explain what I have done so far: First thing I did was to override this class on my default table model:

data = new Object[100][10];
    defaultModel = new DefaultTableModel(data, columnNames) {

        @Override
        public Class<?> getColumnClass(int col) {
            switch(col) {
            case 0:
                return Integer.class;
            case 1:
                return Integer.class;
            case 2:
                return Date.class;
            case 3:
                return String.class;
            case 4:
                return String.class;
            case 5:
                return Boolean.class;
            default:
                return null;
            }
        }


    };

    table = new JTable(defaultModel);
    js = new JScrollPane(table);
    paneLeft.add(js, BorderLayout.CENTER);

And that is how I am trying to populate my table with the checkbox:

 /* My global variables for this part of the code:
String query;
    Statement stmt;
    ResultSet rs;
    DefaultTableModel defaultModel;
    String[] columnNames = {"id","pat_id","date","time", "note", "status"};
*/



public void placeContentIntoRows(){
        stmt = null;
        rs = null;
        query = "select * from messages";

        try {
            stmt = TableConnection.dbConnector().createStatement();
            if (stmt.execute(query)) {
                rs = stmt.getResultSet();
            }

            int rowCounter = 0;

            while(rs.next()){
                data[rowCounter][0] = rs.getInt(1
                data[rowCounter][1] = rs.getInt(2);
                data[rowCounter][2] = rs.getDate("3"); //When I add the right name for all the columns, column status loses its checkbox.
                data[rowCounter][3] = rs.getString(4);
                data[rowCounter][4] = rs.getString(5);
                data[rowCounter][5] = rs.getBoolean(6);

                rowCounter++;    
            }           defaultModel = new DefaultTableModel(data, columnNames);
            table.setModel(defaultModel);

        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
        }

        table.repaint();
    }

You may be able to see that I have this piece of code for column number 3: datarowCounter = rs.getDate("3"); The quotes were added intentionally so that I can explain my problem more fully. When the quotes are there, which means I have a mistake in that part of the code, my table is displayed like that: (With no data, but with the checkbox on it).

CheckBox Displayed

https://i.stack.imgur.com/Ip68h.png

However, if I fix that part of the code and take out the quotes, my table is displayed correctly but without checkboxes!

while(rs.next()){
                data[rowCounter][0] = rs.getInt(1);
                data[rowCounter][1] = rs.getInt(2);
                data[rowCounter][2] = rs.getDate(3); //When I add the right name for all the columns (id), column status loses its checkbox. 
                data[rowCounter][3] = rs.getString(4);
                data[rowCounter][4] = rs.getString(5);
                data[rowCounter][5] = rs.getBoolean(6);

                rowCounter++;    
            }

This is my database table:

  • id int, pat_id int, date date, time varchar(25), note varchar(25), status tinyint(1)

Please do not mind the fact the variable time is set as varchar. Just did it that way for now to tackle a problem at a time. Will change it as soon as I get this checkbox to appear on the screen. 

If anyone could please have a look at my code and try to shed some light on what I am missing that would be much appreciated indeed. That is the first time I work with JTables, so it may be something simple, I know. Just can`t find it myself at this moment. Thank you so very much for your kind help. :)

PS: That`s my table:
Field       | Type          | Null | Key  | Default | Extra
------------+---------------+-------------+---------+-------+
Id          | int (11)      | NO  | Pri   | NULL    | auto_increment
Pat_id      | int (11)      | NO          | NULL
Date        | date          | NO          | NULL    
time        | varchar(25)   | YES         | NULL
note        |varchar(25)    | YES         | NULL
status      |tinyint(1)     | YES         | NULL

Data with no checkbox

https://i.stack.imgur.com/ms5Mn.png

Method where the problem is being noticed refactored:

private void placeContentIntoTable() {
        PreparedStatement st = null;
        ResultSet rst = null;
        try{
            String query="SELECT * from messages";
            st = TableConnection.dbConnector().prepareStatement(query);
            if (st.execute()) rst = st.getResultSet();

                int rowCounter = 0;
                data = new Object[1000][10];
                //String[] columnNames = {"id","pat_id", "date", "time", "note", "status"};
                while(rst.next()){
                    for(int i=0; i<columnNames.length; i++){
                        data[rowCounter][i] = rst.getObject(i+1);
                    }
                    rowCounter++;    
                } 

                defaultModel = new DefaultTableModel(data, columnNames);//When it is uncommented we see data but no checkbox, when it is commented out we see the checkboxes but no data
                table.setModel(defaultModel);

            } catch (SQLException ex) {
                System.out.println("SQLException: " + ex.getMessage());
            }

            table.repaint();
    }
Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81
  • Do you get an Exception? Because I think your date-object is a string and not really a date. So when the table tries to render your column 3, it notices an error and stops dealing with the other columns (hence you losing your checkbox in column 6). This might help: http://stackoverflow.com/questions/36488426/override-getcolumnclass-not-working-for-date-columns – hamena314 Nov 04 '16 at 11:27
  • I cannot understand your current question. Please provide a [SSCCE](http://sscce.org) without retrieval data from the database (for example with a predefined two-dimensional array or something else). In this case we probably can help you. – Sergiy Medvynskyy Nov 04 '16 at 11:53
  • Hello, many thanks for your reply. I have added the picture with the data I have. I don`t get an exception, no. Just can`t see the date with the checkboxes. Have the boolean values as 'true' or 'false' but when I have no correct date to show, I can see the checkboxes. – Francislainy Campos Nov 04 '16 at 11:57
  • Also good to read is [HOWTO for Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html). Simply try to start and modify examples. So you can better understand what's wrong in your program. – Sergiy Medvynskyy Nov 04 '16 at 11:57
  • @hamena314. Sorry, it`s the first time I have a question discussed on Stack overflow, so am not very familiar with it and forgot to add you to my previous reply. Many thanks again for your help! :) – Francislainy Campos Nov 04 '16 at 12:04

2 Answers2

1

Your code appears to be mess up because you have two places where you attempt to create a DefaultTableModel. Once with a custom getColumnClass(...) method and the other without.

defaultModel = new DefaultTableModel(data, columnNames);

You are just using the standard implementation of the DefaultTableModel. The above code does not override the getColumnClass(...) method so the default renderer is used which just invokes the toString() method of the Object in the column.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Hi there, thank you so much for your reply! I think we`re probably on the right track to find what it the problem here. :) After reading your reply I noticed that when I comment out my defaultTableModel the same issue happens. When it is uncommented the data is displayed with no checkbox, but when it is commented the data is not displayed but the checkboxes appear. I will add the refactored method to the description of my problem. You`re saying my code does not override the getColumnClass(...), could you please explain a bit more fully the reason for that and what I should do instead? Thanks! – Francislainy Campos Nov 04 '16 at 16:08
  • @FrancislainyCampos, I already gave you the reason: `you are using the default renderer`. If you want to use a different renderer then you need to override the `getColumnClass(..).` method to return the class of the column so an appropriate renderer can be used. Read the section from the Swing tutorial on [Concepts: Renderers and Editor](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender) for more information. – camickr Nov 04 '16 at 16:44
  • thanks again for you finding the time to help me with that. The only thing that I am not being able to get correctly is the fact you`re saying I am not overriding the getColumnClass. I am sorry I must be missing something very obvious here because if you could please have a second look at the top of the page, where there is the beginning of the description of my problem, I have a piece of code which should be overriding the getColumnClass. Am I doing something wrong there? I am sorry if I am and thank you again! – Francislainy Campos Nov 04 '16 at 17:23
  • @FrancislainyCampos, Once again read my answer!!!!! I stated there are two places where you attempt to create the table model. One overrides the method, the other doesn't. I included the statement causing the problem in my original answer. Find the statement and fix the problem. – camickr Nov 04 '16 at 18:20
  • It`s working now! I took the defaultModel out of the class constructor and pasted it down below on the second part of the code you mentioned. Sorry for the confusion and many thanks for your help. :) – Francislainy Campos Nov 04 '16 at 18:51
  • Done it! Thanks. :) – Francislainy Campos Nov 04 '16 at 19:35
0

The image 2 is not visible, so I am going to take some guesses...

1) Is there anything in the third column?

2) If there is something, is there something in EVERY row?

If the answer to any of those questions is no, then check the quality of your data, is it possible that one of the "Boolean" value is not a Boolean, or an Integer not an Integer, or a Date not a Date (parsing failed on any of those types). I have seen such table construction build OK until it reached such parsing exception, then everything stops and because of the event oriented model for building java table the exception is easily lost and just not handled making the failure invisible to you.

Hope this help,

brou
  • 21
  • 5
  • Hello, many thanks for you finding the time to help me with that. I have added the picture with the data I have. That certainly helps, but if I cant see if I have any wrong data type (aside from the varchar for the time, which I am considering as String in Java anyways).. Thanks again! :) – Francislainy Campos Nov 04 '16 at 12:00
  • So if this works when you have no dates, the problem most probably is there (if it walks like a duck, if it talks like a duck and if it looks like a duck... Well it probably IS a duck) :) So for now, change the date column class to String.class and all should work. When you will be confortable with the checkboxes working from extracted data, fix the dates by using – brou Nov 04 '16 at 12:13
  • Oups... fix the dates by using: – brou Nov 04 '16 at 12:14
  • I will have it... use SimpleDateFormat to convert it from String to Date prior to feeding to your table model. – brou Nov 04 '16 at 12:15
  • Hi again, many thanks for your reply. :) I tried and did that and still get the same problem. To be honest, I dont think the problem may be with the date column because if I input the string "3" or any other one which does not give the right name for the column in the columns before the date, I still get the same problem, with the displaying of the checkboxes with no data, which is expected of course because there i an intended mistake on the input. However, when I have all the column names accordingly, the data is displayed but the checkbox disappears and I just get 'true' or 'false' instead. – Francislainy Campos Nov 04 '16 at 12:58
  • I have added my table to the description of the problem, as I believe this may help? Thank you very much! – Francislainy Campos Nov 04 '16 at 13:38