2013-08-07 25 views
6

Przede wszystkim przepraszam za moje angielskie zaniedbanie, że wyjaśnię cały mój problem.Jak dodać JCheckBox w JTable?

Najpierw chcę JCheckBox w JTable i mam.

Pobieram identyfikator ucznia i nazwisko ucznia z bazy danych w indeksie kolumny 0 i 1. Chcę, aby trzecia kolumna była nieobecna/obecna, która początkowo bierze, czy uczeń jest obecny lub nieobecny przez wartość JCheckbox.

Oto mój kod do wartości JTable:

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

ten kod DLA o wartościach z bazy zapisując go do wektora

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     
} 

Mój problem polega na tym, że nie mogę dodać numeru JCheckBox przed każdym uczniem. Widziałem model JTabel, renderera i wszystko inne, ale nic nie dostałem. Chcę coś takiego ...

enter image description here

mam szukać tych rzeczy na kilka tygodni, ale bot dostać coś odpowiedniego dla tego

+2

PROSZĘ nie krzycz – Dahaka

+0

gdzie jestem krzyczy? Wyjaśniam mój problem. – JavaTweaker

+1

+1 dla kodu i zrzutu ekranu. –

Odpowiedz

8

Zacznij od How to use tables.

Twój model stołu wymaga kilku rzeczy.

  1. Należy zwrócić Boolean.class z metody getColumnClass dla odpowiedniej kolumny. Będziesz musiał zastąpić tę metodę.
  2. Sposób isCellEditable będzie musiał wrócić true dla kolumny tabeli chcesz, aby edytować (dzięki czemu użytkownik może zmienić wartość kolumny)
  3. jesteś modelu tabela będzie musiała być w stanie utrzymać wartość dla kolumna
  4. Upewnij się przekazać poprawną wartość dla kolumny boolean dla rzędu, w przeciwnym razie zostanie on null

Aktualizacja z prostym przykładzie

enter image description here

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 Gorąco polecam unikać redaktorzy formularza dopóki masz lepsze zrozumienie tego, jak działa Swing - IMHO

+0

@mKorbel Naprawdę nie lubię' DefaultTableModel' – MadProgrammer

+0

czy to może być być możliwe bez tworzenia jakiegokolwiek abstrakcyjnego modelu? – Krishna

+1

Naprawdę, tabela wymaga typu klasy, aby kolumna miała wartość typu Boolean, aby działała. – MadProgrammer

1

dobrze, jeśli dodać Boolean wartość jako danych do model tabeli, DefaultCellRendered, sam wyświetli go jako checbox, więc gdzie jest problem?

+2

Niezupełnie. Chyba że 'TableModel # getColumnClass' zwraca' Boolean.class', tabela użyje wartości 'toString' jako wartości do renderered .... – MadProgrammer