Domanda

I have a JTable in my JDialog which I populate myself in another method. Here is my code and I want the second null in my Object array to be a JCheckBox. I have been scowering the internet and saw someone say I need to override a method in the tablerenderer or something like that and I got confused on how to do it. Anyway here is the code

            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                   
    }
È stato utile?

Soluzione

No need for a custom renderer, just override the getColumnClass() method of the DefaultTableModel making the column with the boolean a Boolean object.

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

Altri suggerimenti

why you just don't do a "new JCheckBox()" instead of the second null??

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top