使用Netbeans将JCheckBox添加到JTable

时间:2014-02-13 19:00:54

标签: netbeans jtable jcheckbox

我的JDialog中有一个JTable,我用另一种方法填充自己。这是我的代码,我希望我的Object数组中的第二个null是JCheckBox。我一直在寻找互联网,并看到有人说我需要覆盖tablerenderer中的方法或类似的东西,我对如何做到这一点感到困惑。无论如何这里是代码

            package privatelessontrackernetbeans;

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.TreeMap;
    import javax.swing.ImageIcon;
    import javax.swing.SwingConstants;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;

    /**
     *
     * @author Brent C
     */
    public class WeeklyLessonsReductionGUI extends javax.swing.JDialog {

        /**
         * Creates new form WeeklyLessonsReductionGUI
         * @param parent
         * @param modal
         */
        public WeeklyLessonsReductionGUI(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
            postInitComponents();
        }

        private void postInitComponents() {
            ImageIcon icon = new ImageIcon(PSLTrackerInfo.file + "ymcaLogo.png");
            setIconImage(icon.getImage());
            //Table for students that need more lessons
            DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
            dtm.setRowCount(0);
            //Center the Titles
            DefaultTableCellRenderer centerRenderer = (DefaultTableCellRenderer)
                    jTable1.getTableHeader().getDefaultRenderer();
            centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
            //Center the Cells
            jTable1.setDefaultRenderer(Object.class, centerRenderer);

            TreeMap<Instructor, ArrayList<Student>> theList =
                    PSLTrackerInfo.theList_getMap();
            for (Instructor key : theList.keySet()) {
                ArrayList<Student> students = theList.get(key);
                boolean listed = false;
                for (Student values : students) {
                    Calendar c = Calendar.getInstance();
                    c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
                    c.set(Calendar.WEEK_OF_YEAR, values.getLastUpdateWeek());
                    c.set(Calendar.YEAR, values.getLastUpdateYear());
                    DateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
                    Date date = c.getTime();
                    String s = df.format(date);
                    if (listed) {
                        Object[] data = new Object[]{null,
                                values.getName(), s, null, null, null};
                        dtm.addRow(data);
                    } else {
                        Object[] data = new Object[]{values.getInstructor(),
                                values.getName(), s, null, null, null};
                        dtm.addRow(data);
                        listed = true;
                    }
                }
            }

        }

        /**
         * 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();

            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("Lessons Update");

            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Instructor", "Student", "Last Update", "Lesson Date", "Lesson Complete", "Unscheduled Lessons"
                }
            ) {
                boolean[] canEdit = new boolean [] {
                    false, false, false, false, true, true
                };

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            jScrollPane1.setViewportView(jTable1);

            jButton1.setText("Update");

            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.DEFAULT_SIZE, 829, Short.MAX_VALUE)
                    .addContainerGap())
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(375, 375, 375))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );

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


        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                   
    }

2 个答案:

答案 0 :(得分:2)

无需自定义渲染器,只需覆盖getColumnClass()的{​​{1}}方法,即使DefaultTableModel boolean Boolean对象生成该列。

enter image description here

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class CheckBoxTable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Object[][] data
                        = {{"false", false},
                            {"true", true}};

                String[] cols = {"String", "Boolean"};
                DefaultTableModel model = new DefaultTableModel(data, cols) {
                    @Override
                    public Class<?> getColumnClass(int column) {
                        if (column == 1) {
                            return Boolean.class;
                        } else {
                            return String.class;
                        }
                    }
                };

                JTable table = new JTable(model);
                JOptionPane.showMessageDialog(null, new JScrollPane(table));
            }
        });
    }
}

答案 1 :(得分:0)

为什么你不做“新的JCheckBox()”而不是第二个null ??