0

I have managed to create a table in eclipse. The table has rows that are numbered. Here is the code:

public class JTableRowHeader {

    private JFrame frame = new JFrame("JTable RowHeader");
    private JScrollPane scrollPane;
    private JTable table;
    private DefaultTableModel model;
    private TableRowSorter<TableModel> sorter;
    private JTable headerTable;
    private JCheckBox chckbxNewCheckBox; // declared check box
    private JCheckBox all;
    //private List<JCheckBox> checkBoxes;


    public JTableRowHeader() {
        int NoOfRows = 60;
        table = new JTable(NoOfRows, 2);
        for (int i = 0; i < table.getRowCount(); i++) {
            table.setValueAt(i, i, 0);
        }
        sorter = new TableRowSorter<TableModel>(table.getModel());
        table.setRowSorter(sorter);
        model = new DefaultTableModel() {

        };



        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                model.fireTableRowsUpdated(0, model.getRowCount() - 1);
            }
        });
        scrollPane = new JScrollPane(table);
        scrollPane.setRowHeaderView(headerTable);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(scrollPane);

        chckbxNewCheckBox = new JCheckBox("New check box");
        scrollPane.setColumnHeaderView(chckbxNewCheckBox);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if (info.getName().equals("Nimbus")) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JTableRowHeader TestTableRowHeader = new JTableRowHeader();
                frame.add(new CheckBoxGroup(); //trying to add the check box
            }
        });
    }
}

Now that I have created the table I wish to add a checkbox for all the rows in the table. I also want the checkboxes to cahnge when I change the number of rows in the table for example if I have 4 rows I want 4 checkboxes and if I increase it to 60 rows I want 60 checkboxes. I have tried a few attempts but have failed. I am fairly new to this so any help using my code will be appreciated.

Ansharja
  • 1,237
  • 1
  • 14
  • 37
David Gardener
  • 93
  • 2
  • 13

2 Answers2

2

Read the section from the Swing tutorial on How to Use Tables for the basics and working examples to get you started.

The keys are:

  1. You need to override the getColumnClass(...) method of your DefaultTableModel to return Boolean.class for the column with the combo boxes.

  2. Then in your loop where you set the data you will need to add data to your TableModel.

So the code would be something like:

table.setValueAt(i, i, 0);
table.setValueAt(Boolean.FALSE, I, 1); // add the check box

I want to do it without the Object[ ] method

Yes, well that is the better approach. You should never create a TableModel with a fixed size. Create the table with 0 rows and then just use the addRow(...) method to let the table dynamically grow as you add rows of data.

This is better than using setValueAt(...).

TT.
  • 15,774
  • 6
  • 47
  • 88
camickr
  • 321,443
  • 19
  • 166
  • 288
1

You must create a pattern that contains a boolean field (which is displayed with the default checkbox)

public class MyTableModel extends DefaultTableModel implements TableModel {

    private List<JCheckBox> list;

    public List<JCheckBox> getList() {
        return list;
    }

    public void setList(List<JCheckBox> list) {
        this.list = list;
        fireTableDataChanged();
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public int getRowCount() {
        if(list != null) {
            return list.size();
        }

        return super.getRowCount();
    }

    @Override
    public Class<?> getColumnClass(int column) {
        if(column == 0) {
            return Boolean.class;
        }

        return super.getColumnClass(column);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return column == 0;
    }

    @Override
    public Object getValueAt(int row, int column) {
        if(column == 0) {
            return list.get(row).isSelected();
        }

        return "";
    }

    @Override
    public void setValueAt(Object aValue, int row, int column) {
        if(column == 0) {
            list.get(row).setSelected((Boolean) aValue);
        }
    }
}

And this is, for example, initializing with an array / List of JCheckBox objects (though there is no particular practical meaning ...)

public class JTableRowHeader {
    private JFrame frame;
    private JScrollPane scrollPane;
    private JTable table;

    public JTableRowHeader() {
        table = new JTable(new MyTableModel());
        scrollPane = new JScrollPane(table);

        frame = new JFrame("JTable RowHeader");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JTableRowHeader testTableRowHeader = new JTableRowHeader();

            JCheckBox checkBoxes[] = new JCheckBox[60];
            for(int i = 0; i < checkBoxes.length; i++) {
                checkBoxes[i] = new JCheckBox("Check box " + i);
            }

            ((MyTableModel)testTableRowHeader.table.getModel()).setList(Arrays.asList(checkBoxes));
        });
    }
}
mr mcwolf
  • 2,574
  • 2
  • 14
  • 27
  • (1-) This model will only support a single column with check boxes. You won't be able to have other columns of data. There is no need to create a completely new TableModel. – camickr Nov 02 '17 at 14:57
  • Not need? "You need to override the getColumnClass(...) method of your DefaultTableModel to return Boolean.class for the column with the combo boxes." - this did not you write it to you? – mr mcwolf Nov 02 '17 at 15:57
  • The key words are "completely new". There is no need to override getRowCount(), getColumnCount(), getValueAt(), setValueAt() etc. In fact the you added will break the basic functionality of the DefaultTableModel. That is why I said you only need to override the `getColumnClass(...)` method. – camickr Nov 02 '17 at 16:44