1

I have JTable and I fill it with SQL data, here is my method:

private void updateTable() {
    try {
        String sql = "SELECT number as Numver, name as Available, type FROM available_t ORDER BY number asc";
        pst = conn.prepareStatement(sql);
        rs = pst.executeQuery();
        tableAvail.setModel(DbUtils.resultSetToTableModel(rs));

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    } finally {
        try {
            rs.close();
            pst.close();
        } catch (Exception e) {
        }
    }
}

So far so good. The data shows correct. But, I want to put one more column with checkbox. When I try to create manually using wizard in Eclipse (button 'model') I can't add new column, maybe because the table and columns is create by method. So, How I can add new column, that will have checkboxes. Then after I select some checkbox - when I press OK button, to check which checkboxes are checked and update it in db in column TYPE with YES or NO.

Edit:*** Here is my code, I just want result true/false to be converted in checkboxes in column:

private JPanel contentPane;
private final JPanel panel = new JPanel();
private final JScrollPane scrollPane = new JScrollPane();
private final JTable table = new JTable();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TableExample frame = new TableExample();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public TableExample() {
    initGUI();
}
private void initGUI() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    panel.setBounds(31, 11, 238, 209);

    contentPane.add(panel);
    panel.setLayout(null);
    scrollPane.setBounds(10, 11, 218, 187);

    panel.add(scrollPane);
    table.setModel(new DefaultTableModel(
        new Object[][] {
            {"1", "Test1", "20", "false"},
            {"2", "Test2", "10", "false"},
            {"3", "Test3", "20", "true"},
        },
        new String[] {
            "Id", "Test", "Rate", "T/F"
        }
    ));

    scrollPane.setViewportView(table);
}
Rumen
  • 137
  • 6
  • 22
  • 2
    please did you read offical Oracle tutorial - How to use Table, practically most of parts are about (or including something about), short_cut a DbUtils must returns proper data type – mKorbel Aug 26 '15 at 08:24
  • Yes, I read it, I try it, but I still learning java, it's hard to understand. – Rumen Aug 26 '15 at 08:36
  • short_cut a DbUtils must returns a Boolean – mKorbel Aug 26 '15 at 08:49
  • The [default renderer/editor](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender) should work. If not, please edit your question to include a [complete example](http://stackoverflow.com/help/mcve) that shows your approach. – trashgod Aug 26 '15 at 08:50
  • `mKorbel`, I can't understand what is short_cut :) `trashgod`, so, let say, I want for now, with those data in table, to add one more column with checkboxes, then I will try to check if some checkbox is selected, to invoke SQL query to update in db. – Rumen Aug 26 '15 at 10:35
  • *** I edited my question – Rumen Aug 26 '15 at 11:17
  • not - "false" but false or new Boolean(false), e.g. DefaultTableModel by default knows data types (part Renderer and Editors) but {new Integer(1), new String("Test1"), new Double(20).0, false}, – mKorbel Aug 26 '15 at 12:06

2 Answers2

1

You need to override the getColumnClass(...) method to return the class of the data in the column so the table can use the proper renderer/editor.

Something like:

JTable table = new JTable( model )
{
    @Override
    public Class getColumnClass(int column)
    {
        for (int row = 0; row < getRowCount(); row++)
        {
            Object o = getValueAt(row, column);

            if (o != null)
            {
                return o.getClass();
            }
        }

        return Object.class;
    }
};
camickr
  • 321,443
  • 19
  • 166
  • 288
0

thanks everyone. Here is what I create and works perfect

public void updateTable() throws ClassNotFoundException, SQLException {
 String sql = "select * from instruments_sales_t where sold = 'YES'";
 conn = ConnectionToDb.connectDb();
 stmt = conn.createStatement();
 rs = stmt.executeQuery(sql);


 DefaultTableModel model = new DefaultTableModel() {
 public Class<?> getColumnClass(int column) {
 switch (column) {

 case 0: return String.class;
 case 1: return String.class;
 case 2: return String.class;
 case 3: return String.class;
 case 4: return String.class;
 case 5: return String.class;
 case 6: return String.class;
 case 7: return Boolean.class;

 default:return String.class;
 }
 }
 };


 tablePaidSales.setModel(model);
 model.addColumn("id");
 model.addColumn("Name");
 model.addColumn("Size");
 model.addColumn("Avail");
 model.addColumn("Total");
 model.addColumn("Cl");
 model.addColumn("Date");
 model.addColumn("");

 int i = 0;
 while (rs.next()) {
 model.addRow(new Object[0]);
 model.setValueAt(rs.getString("id"), i, 0);
 model.setValueAt(rs.getString("name"), i, 1);
 model.setValueAt(rs.getString("size"), i, 2);
 model.setValueAt(rs.getString("want_items"), i, 3);
 model.setValueAt((rs.getDouble("want_price"))*(rs.getDouble("want_items")), i, 4);
 model.setValueAt(rs.getString("client"), i, 5);
 model.setValueAt(rs.getString("date_of_sell"), i, 6);
 model.setValueAt(false, i, 7);
 i++;
 }

      DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
      rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
 rightRenderer.setForeground(Color.BLUE);

 DefaultTableCellRenderer redRenderer = new DefaultTableCellRenderer();
 redRenderer.setHorizontalAlignment(JLabel.RIGHT);
 redRenderer.setForeground(Color.RED);

 tablePaidSales.setShowGrid(true);
 tablePaidSales.setGridColor(Color.LIGHT_GRAY);
 tablePaidSales.setShowHorizontalLines(false);
 tablePaidSales.getColumnModel().getColumn(0).setPreferredWidth(28);
 tablePaidSales.getColumnModel().getColumn(1).setPreferredWidth(230);
 tablePaidSales.getColumnModel().getColumn(2).setPreferredWidth(140);
 tablePaidSales.getColumnModel().getColumn(3).setPreferredWidth(57);
 tablePaidSales.getColumnModel().getColumn(4).setPreferredWidth(70);
 tablePaidSales.getColumnModel().getColumn(5).setPreferredWidth(120);
 tablePaidSales.getColumnModel().getColumn(6).setPreferredWidth(82);
 tablePaidSales.getColumnModel().getColumn(7).setPreferredWidth(25);
 tablePaidSales.getColumnModel().getColumn(3).setCellRenderer(rightRenderer);
 tablePaidSales.getColumnModel().getColumn(4).setCellRenderer(redRenderer);
 }
Rumen
  • 137
  • 6
  • 22