带有Checkbox的Java结果集到JTable

时间:2015-09-25 10:26:10

标签: java

我有这个代码可以显示数据库中的数据。它运作良好,但我希望它在最后一栏有复选框。我在这里找到了一些代码,但它仅适用于预先定义的非值而不是数据库。 (How to add checkboxes to JTABLE swing

截图:

Here is my screenshot of my JTable:

代码:

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);    
    }
}

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

    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;
        }
    }
}

如果您还想要复选框可编辑,则还必须设置TableCellEditor。

答案 1 :(得分:0)

最简单的方法是不使用DBUtils并自己将ResultSet中的数据加载到TableModel中。

代码并不困难,您可以使用Table From Database中的Table From Database Example作为起点。

代码只是将ResultSet中的数据加载到Vectors中,因此您可以手动添加另一列以包含布尔数据。

对代码的更改类似于:

//  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 );
}

另一种选择是创建一个&#34;包装器&#34;使用DBUtils TableModel包装布尔列的TableModel。查看How to add checkbox in Jtable populated using rs2xml以获取此方法的示例。

该答案将复选框列放在表格的开头,因此您需要修改代码以将复选框放在最后。