簡體   English   中英

如何在JTable中添加JCheckBox?

[英]How to add JCheckBox in JTable?

首先,我為我的英語疏忽表示歉意,我將解釋我所有的問題。

首先,我想在JTable中擁有JCheckBox。

我正在從列索引0和1的數據庫中檢索學生ID和學生姓名。我希望第三列應該是“缺席/在場”,這將首先根據JCheckbox值來確定學生是否在場。

這是我的JTable值代碼:

出勤率

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

此代碼可從數據庫中獲取值,並將其保存到矢量中

出勤GUI.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                   
}

我的問題是我無法在看到JTabel模型,渲染器和所有其他對象的每個學生面前添加JCheckBox ,但我什么也沒得到。 我想要這樣的東西

在此處輸入圖片說明

我已經搜索了幾周,但是機器人卻沒有找到適合的東西

如何使用表格開始

您的表模型需要幾件事。

  1. 它需要從getColumnClass方法的適當列返回Boolean.class 您將需要重寫此方法。
  2. isCellEditable方法將需要為要使其可編輯的表列返回true (以便用戶可以更改列的值)
  3. 您的表模型將需要能夠保存列的值
  4. 確保為該行的boolean列傳遞一個有效值,否則它將為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);
      }
    }

  }

}

附:我強烈建議您避免使用表單編輯器,直到您對Swing的工作方式有了更好的了解-IMHO

好吧,如果您將Boolean值作為數據添加到表模型中, DefaultCellRendered會將其自身呈現為checbox,那么問題出在哪里呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM