如何在 JTable 中添加 JCheckBox?

2022-01-24 00:00:00 sql java swing jframe

首先我为我的英语疏忽道歉,我会解释我所有的问题.

First of all i apologize for my english neglect that i will explain all my problem.

首先我想要 JTable 中的 JCheckBox.

First i want JCheckBox in the JTable i have.

我正在从数据库中的列索引 0 和 1 中检索学生 ID 和学生姓名.我希望第三列应该是 Absent/Present,它最初将通过 JCheckbox 值判断学生是否存在.

I am retrieving student id and student name from database in column index 0 and 1. I want third column should be Absent/Present which will initially take whether student is present or absent by JCheckbox Value.

这是我的 JTable 值代码:

Here my code for JTable values :

Attendance.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shreesai;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

/**
 *
 * @author Admin
 */
public class Attendance{

    Connection con = Connectdatabase.ConnecrDb();
    public Vector getEmployee()throws Exception
    {

        Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();

        PreparedStatement pre = con.prepareStatement("select studentid,name from student");
        ResultSet rs = pre.executeQuery();
        while(rs.next())
        {

            Vector<String> employee = new Vector<String>();
            employee.add(rs.getString(1)); //Empid
            employee.add(rs.getString(2));//name
            employeeVector.add(employee);

        }        
        if(con!=null)
        con.close();
        rs.close();
        pre.close();

        return employeeVector;
    }
}

此代码用于从数据库中获取值并将其保存到向量中

AttendanceGUI.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shreesai;

import static java.awt.Frame.MAXIMIZED_BOTH;
import java.util.Vector;
import javax.swing.JOptionPane;

/**
 *
 * @author Admin
 */
public class AttendanceGUI extends javax.swing.JFrame {

    /**
     * Creates new form AttendanceGUI
     */
    private Vector<Vector<String>> data;
    private Vector<String> header;
    public AttendanceGUI() throws Exception {

        this.setLocationRelativeTo(null);
        setExtendedState(MAXIMIZED_BOTH);
        Attendance att = new Attendance();
        data = att.getEmployee();

        header = new Vector<String>();
        header.add("Student ID");
        header.add("Student Name");
        header.add("Absent/Present");
        initComponents();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        AttendanceT = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
            data,header
        ));
        jScrollPane1.setViewportView(AttendanceT);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(397, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(89, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try{
                    new AttendanceGUI().setVisible(true);
                }
                catch(Exception e){
                    JOptionPane.showMessageDialog(null,e);
                }
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTable AttendanceT;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                   
}

我的问题是我无法在我见过的每个学生面前添加 JCheckBox 模型、渲染器和所有东西,但我什么也没得到.我想要这样的东西......

My problemis that I can't add a JCheckBox in front of every student I have seen JTabel model, renderer and all but I don't get anything. I want something like this...

我已经搜索这个东西几个星期了,但 bot 有没有找到适合这个的东西

I've search for this stuff for a couple of weeks but did bot get anything suitable for this

推荐答案

从如何使用表格.

您的表格模型需要几样东西.

Your table model needs several things.

  1. 它需要从 getColumnClass 方法为相应的列返回 Boolean.class.您将需要覆盖此方法.
  2. isCellEditable 方法需要为您想要使其可编辑的表列返回 true(以便用户可以更改列的值)
  3. 您的表格模型需要能够保存列的值
  4. 确保为该行的 boolean 列传递一个有效值,否则将为 null
  1. It needs to return Boolean.class from the getColumnClass method for the appropriate column. You will need to override this method.
  2. The method isCellEditable will need to return true for the table column you want to make editable (so the user can change the value of the column)
  3. You're table model will need to be capable of holding the value for the column
  4. Make sure you pass a valid value for the boolean column for the row, otherwise it will be null

用简单的例子更新

import java.awt.EventQueue;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TableTest {

  public static void main(String[] args) {
    new TableTest();
  }

  public TableTest() {
    startUI();
  }

  public void startUI() {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
          ex.printStackTrace();
        }

        MyTableModel model = new MyTableModel();
        model.addRow(new Object[]{0, "Brian", false});
        model.addRow(new Object[]{1, "Ned", false});
        model.addRow(new Object[]{2, "John", false});
        model.addRow(new Object[]{3, "Drogo", false});
        JTable table = new JTable(model);

        JFrame frame = new JFrame("Testing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(table));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    });
  }

  public class MyTableModel extends DefaultTableModel {

    public MyTableModel() {
      super(new String[]{"ID", "Name", "Present"}, 0);
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
      Class clazz = String.class;
      switch (columnIndex) {
        case 0:
          clazz = Integer.class;
          break;
        case 2:
          clazz = Boolean.class;
          break;
      }
      return clazz;
    }

    @Override
    public boolean isCellEditable(int row, int column) {
      return column == 2;
    }

    @Override
    public void setValueAt(Object aValue, int row, int column) {
      if (aValue instanceof Boolean && column == 2) {
        System.out.println(aValue);
        Vector rowData = (Vector)getDataVector().get(row);
        rowData.set(2, (boolean)aValue);
        fireTableCellUpdated(row, column);
      }
    }

  }

}

Ps- 我强烈建议您避免使用表单编辑器,直到您更好地了解 Swing 的工作原理 - 恕我直言

Ps- I would HIGHLY recommend you avoid form editors until you have a better understanding of how Swing works - IMHO

相关文章