简体   繁体   中英

add jcheckBox to Jtable using GUI

after searching in google and stackoverflow and going over some answers i'm still stuck with this problem.

i've jtable and i'm filling it from database(derpy-JDBC). i want add check box to my jtable using GUI ..i have change column type to boolean and add these lines

JCheckBox checkBox = new javax.swing.JCheckBox();
jTable1.getColumn("status").setCellEditor(new DefaultCellEditor(checkBox));

but it doesn't work correctly. this my try

public class showp1 extends javax.swing.JFrame implements  ActionListener  {

    /** Creates new form showp1 */
    public showp1() {
        initComponents();
        this.setLocationRelativeTo(null);
        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
      jTextField1.addActionListener(this);

    }

    /** 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();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "id", "area", "location", "status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("jButton1");

        jButton2.setText("jButton2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(73, 73, 73)
                            .addComponent(jButton2)
                            .addGap(166, 166, 166))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))))
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(64, 64, 64))
        );

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

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  

       myDbConnection dbconnect;
        // TODO add your handling code here:


               ArrayList<String> list = new ArrayList<String>();
        try {

         dbconnect = new myDbConnection();
            ResultSet resultSet =null;
            resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 FROM pledges ");



                while (resultSet.next()){
                   list.add(resultSet.getString(1));
                    list.add(resultSet.getString(2));
                    list.add(resultSet.getString(3));
                    list.add(resultSet.getString(4));
                }


        } catch (Exception e) {
            System.out.println(e);
        }

        Object[][] record;

        int myListCount = list.size()/4;
        record = new Object[myListCount][4];
        int count = 1;
       // JCheckBox checkBox = new javax.swing.JCheckBox();
        for (int ii = 1; ii<=myListCount;ii++) {
            for(int i=1;i<=4;i++){
                record[ii-1][i-1] = list.get(count-1);
                count++;

            }

        }
        //TableColumnModel columnModel = jTable1.getColumnModel();
         //columnModel.getColumn(3).setCellEditor(new DefaultCellEditor(checkBox));

        jTable1.setModel(new DefaultTableModel(record, new String[]{"id", "area", "location","status1"}) {
        @Override
     public Class<?> getColumnClass(int columnIndex) {
        if (getColumnName(columnIndex).equals("status1")) {
           return Boolean.class;
        }
        return super.getColumnClass(columnIndex);
     }
  });


 public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new showp1().setVisible(true);
            }
        });
} }

sorry for this awful code^^" thanks in advance

Read the Oracle Swing JTable tutorial and you'll see that you don't need to use a cell renderer or editor directly, that all you need to do is to return the correct column class of Boolean.class, and Swing will supply the correct renderer and editor for you. This is done by overriding the TableModel's getColumnClass(int column) method.

eg,

  jTable1.setModel(new DefaultTableModel(record, new String[]{"id", "area", "location",
     "status1"}) {
     @Override
     public Class<?> getColumnClass(int columnIndex) {
        if (getColumnName(columnIndex).equals("status1")) {
           return Boolean.class;
        }
        return super.getColumnClass(columnIndex);
     }
  });

Note that for this to work record needs to be a 2-dimensional array of Object[][], not of String[][], and the status1 column must hold Boolean data, not String data, but that should be easy enough for you to fix when you are populating the record array in your nested for loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM