2

I have this code to which it can display data from database. It's working well but I want it to have checkbox at last column. I've found some codes here but It's only for pre-defined not values and not from database. (How to add checkboxes to JTABLE swing)

Screenshot:

Here is my screenshot of my JTable:

Code:

public print() {
    initComponents();
    try{
        conn = (Connection) db_connect.connectDB();
    }
    catch(ClassNotFoundException | SQLException ex){
        JOptionPane.showMessageDialog(null, ex);
    }
    update_table("select name, section, student_number, gender from students");
}

public void update_table(String q){
    try{
            st= conn.createStatement();
            st.executeQuery(q);
            ResultSet rs = st.executeQuery(q);
            users_list.setModel(DbUtils.resultSetToTableModel(rs));  

            users_list.getColumnModel().getColumn(0).setPreferredWidth(250);
            users_list.getColumnModel().getColumn(0).setPreferredWidth(250);
            users_list.getColumnModel().getColumn(1).setPreferredWidth(150);
            users_list.getColumnModel().getColumn(2).setPreferredWidth(120);
            users_list.getColumnModel().getColumn(3).setPreferredWidth(100);

            int count= users_list.getModel().getRowCount(); 
            if(count==0){
                no_results_found.setVisible(true);
            }
            else{
                no_results_found.setVisible(false);
            }
    }
    catch(SQLException ex){
        JOptionPane.showMessageDialog(null,ex);    
    }
}
Community
  • 1
  • 1
tokis
  • 125
  • 1
  • 4
  • 14
  • IMO you first need a table with a checkbox in the last column. Then you want to set the checkbox according to the database values. So please show your code with the table , checkboxes included. – Bö macht Blau Sep 25 '15 at 10:40
  • This is not related, but you are executing the query twice – Ron C Sep 25 '15 at 10:41
  • possible duplicate of [How to render a checkbox in a JTable?](http://stackoverflow.com/questions/4154802/how-to-render-a-checkbox-in-a-jtable) – roeygol Sep 25 '15 at 10:43

2 Answers2

0

You can try something like this:

    public class JTableWithCheckBox {

    private JFrame mainFrame;
    private JTable studentTable;
    private JScrollPane scrollPaneTable;

    private DefaultTableModel model = new DefaultTableModel(new Object[][] {
            { "Ramesh", "Male" }, { "Sheela", "Female" },
            { "Amithabh", "Male" }, { "Katrina", "Female" } }, new Object[] {
            "Name", "Gender" });

    public static void main(String[] args) {
        final JTableWithCheckBox ui = new JTableWithCheckBox();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ui.initGUI();
            }
        });
    }

    private void initGUI() {
        mainFrame = new JFrame("View");
        mainFrame.getContentPane().setLayout(new BorderLayout());
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(300, 200);
        mainFrame.setVisible(true);
        mainFrame.setLocationRelativeTo(null);

        studentTable = new JTable(model);
        studentTable.getColumnModel().getColumn(1)
                .setCellRenderer(new MFCheckBox());
        scrollPaneTable = new JScrollPane(studentTable);
        mainFrame.add(scrollPaneTable, BorderLayout.NORTH);

    }

    private class MFCheckBox implements TableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row,
                int column) {
            JPanel cbPanel = new JPanel();
            JCheckBox maleBox = new JCheckBox("Male");
            JCheckBox femaleBox = new JCheckBox("Female");

            cbPanel.setLayout(new BorderLayout());
            cbPanel.add(maleBox, BorderLayout.WEST);
            cbPanel.add(femaleBox, BorderLayout.EAST);

            if (value != null) {
                if (value instanceof String) {
                    String valStr = (String) value;
                    switch (valStr) {
                    case "Male":
                        maleBox.setSelected(true);
                        femaleBox.setSelected(false);
                        break;
                    case "Female":
                        maleBox.setSelected(false);
                        femaleBox.setSelected(true);
                        break;
                    default:
                        maleBox.setSelected(false);
                        femaleBox.setSelected(false);
                        break;
                    }
                }
            }
            return cbPanel;
        }
    }
}

If you also want checkbox editable, you will have to set TableCellEditor as well.

0

The easiest way is to NOT use DBUtils and to load the data from the ResultSet into the TableModel` yourself.

The code is not difficult and you can use the Table From Database Example found in Table From Database as the starting point.

The code just loads the data from the ResultSet into Vectors, so you can then manually add another column to contain Boolean data.

The changes to the code would be something like:

//  Get column names

for (int i = 1; i <= columns; i++)
{
    columnNames.addElement( md.getColumnName(i) );
}

columnName.addElement( "Check Mark" ); // added

//  Get row data

while (rs.next())
{
    Vector<Object> row = new Vector<Object>(columns);

    for (int i = 1; i <= columns; i++)
    {
        row.addElement( rs.getObject(i) );
    }

    row.addElement( Boolean.FALSE ); // added
    data.addElement( row );
}

The other option is to create a "wrapper" TableModel that wraps a Boolean column with your DBUtils TableModel. Check out How to add checkbox in Jtable populated using rs2xml for an example of this approach.

That answer places the check box column at the start of the table, so you would need to modify the code to place the check box at the end.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288