How to select all the rows of a JTable?

1.7k views Asked by At

I am trying to make a JTable which stores boolean checkboxes, previous browsing time, sites and their URL. I have added a menu bar in it which contains two menu items Remove and Select All.

My problem is with Select All .I want to select all rows of table by clicking it. But when i click it, it makes all elements of checkBox(given below) true but doesn't show it in the table. I mean i can't see any selected tick marks in the table.

Here is my code below. Where did i go wrong? Any help would be really appreciated.

public class HistList extends JPanel {

JTable table = new JTable();
Object[][] data;
public static ArrayList<String> timeList;
public static ArrayList<String> namelist;
public static ArrayList<String> locTable;
JMenuItem remove = new JMenuItem("Remove");
JMenuItem selectAll = new JMenuItem("Select All");
JScrollPane scrollPane = new JScrollPane();
MyTableModel model = new MyTableModel();
int i = 0;
Hello hello;
public static ArrayList<Boolean> checkBox = new ArrayList<>();

HistList(ArrayList timeList, ArrayList namelist, ArrayList locTable) {
    try {
        UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    }
    count = new ArrayList<>();
    this.dateList = dateList;
    this.locTable = locTable;
    this.namelist = namelist;
    this.timeList = timeList;
    this.repeatCount = repeatCount;
    String[] title = {" ", "Time", "Name", "Location"};
        data = new Object[this.title.size()][4];
        for (int j = 0; j < data.length; j++) {
            for (int k = 0; k < 4; k++) {
                if (k == 0) {
                    data[j][k] = false;
                } else if (k == 1) {
                    data[j][k] = this.timeList.get(j);
                } else if (k == 2) {
                    data[j][k] = this.namelist.get(j);
                } else if (k == 3) {
                    data[j][k] = this.locTable.get(j);
                }
            }
        }
    for (int i = 0; i < data.length; i++) {
        model.addRow(data[i]);
        checkBox.add(false);
    }
    this.table = new JTable(model);
    this.table.setShowGrid(false);

    this.scrollPane = new JScrollPane(this.table);
    Dimension size = new Dimension(510, 380);
    this.scrollPane.setPreferredSize(size);
    JPanel contentPane = new JPanel();
    contentPane.add(scrollPane);
    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 1) {
                JTable target = (JTable) e.getSource();
               //do something
            }
            if (e.getClickCount() == 2) {
                try {
                    JTable target = (JTable) e.getSource();
                    int row = target.getSelectedRow();
                    //do something
                } catch (IOException ex) {
                    Logger.getLogger(HistList.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    JMenuBar organize = new JMenuBar();
    JMenu menu = new JMenu("Organize");
    menu.add(remove);
    menu.add(selectAll);
    selectAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            System.out.println("in select all");
            checkBox.clear();
            for(int i=0;i<model.getRowCount();i++)
            model.setValueAt(true, i,0 );
            table.revalidate();
            table.validate();
        }
    });
    selectAll.setEnabled(true);
    remove.setEnabled(false);
    remove.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            int num = 0;
            for (int j = model.getRowCount() - 1; j >= 0; j--) {
                System.out.println(model.getValueAt(j, 2));
                System.out.println(model.getRowCount());
                if (checkBox.get(j)) {
                    model.removeRow(j);
                    model.fireTableDataChanged();
                }
            }
        }
    });
    organize.add(menu);

    JPanel finale = new JPanel(new BorderLayout());
    finale.add(organize, BorderLayout.NORTH);
    finale.add(contentPane, BorderLayout.CENTER);
    add(finale);
}

public void createAndShowGUI() {
    JFrame frame = new JFrame("History");
    HistList newContentPane = new HistList(timeList, namelist, locTable);
    newContentPane.setOpaque(true); 
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
}

public class MyTableModel extends DefaultTableModel {

    public MyTableModel() {
        super(new String[]{" ", "Time", "Name", "Location"}, 0);
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
        }
        Class clazz = String.class;
        switch (columnIndex) {
            case 0:
                clazz = Boolean.class;
                break;
        }
        return clazz;
    }

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

    @Override
    public void setValueAt(Object aValue, int row, int column) {
        if (aValue instanceof Boolean && column == 0) {

            Vector rowData = (Vector) getDataVector().get(row);
            rowData.set(0, (boolean) aValue);
            if (checkBox.size() > row) {
                checkBox.remove(row);
            }
            checkBox.add(row, (Boolean) aValue);
            System.out.println(row + " " + checkBox.toString());
            if (checkBox.contains(true)) {
                remove.setEnabled(true);
            } else {
                remove.setEnabled(false);
            }
        }
    }

}
}
3

There are 3 answers

0
Edwin Torres On BEST ANSWER

Here's a simple example that may help. Clicking the button sets the Boolean value of the checkbox cells to true:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {

        setLayout(new GridLayout(2,1));

        Object[] columnNames = {"Check"};
        Object[][] data = { {false}, {false}, {false}, {false} };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {
            private static final long serialVersionUID = 1L;
            @Override
            public Class getColumnClass(int column) {
                return Boolean.class;
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        JButton btn = new JButton("Check All");
        btn.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
                for (int row=0; row < table.getRowCount(); row++) {
                    table.setValueAt(true, row, 0);
                }
            } 
        } );
        add(btn);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}
0
az fav On
    if (buttonclicked) {
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            jTable1.setValueAt(true, i, 0);
        }
    } else {
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            jTable1.setValueAt(false, i, 0);
        }
    }

This code Selects All checkboxs on the same column and deselects when you ,for example , uncheck checkbox.

0
AudioBubble On

Simply apply basic code of JTable in selecting the data/s. Ex. jTable.SelectAll() which allow the user to select all the data within the table.