Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put a "(de)select all" check box in an SWT Table header?

Tags:

java

checkbox

swt

I have an SWT Table that I'm instantiating with the SWT.CHECK style in order to display a check box next to every row. My users have requested another check box in the header row of the table in order to allow them to select/deselect all the rows with one click.

I can't see any obvious way to do it, and I've only found Swing/JTable examples through Google. Does anyone know how to do this? I'm hoping it's possible without re-implementing Table or falling back on a header context menu.

like image 603
Martin McNulty Avatar asked Aug 19 '10 10:08

Martin McNulty


1 Answers

Just create two images of check box. First one without a tick and second one having a tick.Now add the first image to the tableColumn header. After that add listener to tableColumn in such a way that when you click button for the first time, table.selectALL() method should be fired along with changing the tableColumn header image to second one. When you click button again call table.deSelectAll() method and replace the tableColumn header with the first image.

You can use this condition:

When the checkbox(image) is clicked, use a for loop to check whether, any of the checkboxes in the table is checked. if anyone is found checked then fire table.deSelectAll() method , else fire table.selectAll() method.

There will not be any problem for the "checkbox" during table/widow resizing.

tableColumn0.addListener(SWT.Selection, new Listener() {
    @Override
    public void handleEvent(Event event) {
        // TODO Auto-generated method stub
        boolean checkBoxFlag = false;
        for (int i = 0; i < table.getItemCount(); i++) {
            if (table.getItems()[i].getChecked()) {
                checkBoxFlag = true;
            }
        }

        if (checkBoxFlag) {
            for (int m = 0; m < table.getItemCount(); m++) {
                table.getItems()[m].setChecked(false);
                tableColumn0.setImage(new Image(Display.getCurrent(),
                        "images/chkBox.PNG"));

                table.deselectAll();

            }
        } else {
            for (int m = 0; m < table.getItemCount(); m++) {
                table.getItems()[m].setChecked(true);
                tableColumn0.setImage(new Image(Display.getCurrent(),
                        "images/chkBox2.PNG"));

                table.selectAll();
            }
        }

    }
});
like image 88
Suraj.c.s Avatar answered Oct 21 '22 06:10

Suraj.c.s