Solved

add check box and listener in table

Posted on 2004-04-25
34
1,344 Views
Last Modified: 2008-02-01
I have a table and i want to add the checkbox and checkbox listener at the left hand side. But how can i add it?

thanks
0
Comment
Question by:Kennywen
  • 15
  • 6
  • 5
  • +3
34 Comments
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10915994
u want to add the checkbox within the table

or

??


Regards,
Muruga
0
 

Author Comment

by:Kennywen
ID: 10916008
yes, i want to add the checkbox within the table. (E.g. when user click on the particular checkbox then i will do something on the data for the specify row.)

thanks
0
 
LVL 9

Accepted Solution

by:
mmuruganandam earned 25 total points
ID: 10916022
See the below examples..

http://www.codeguru.com/java/articles/665.shtml
http://quicktable.org/jtable/quicktablemain.htm


These might help you in having JCheckBox in a Cell of JTable.
0
 
LVL 92

Expert Comment

by:objects
ID: 10916069
Just add Boolean's to a model something like:

public class MyTableModel extends DefaultTableModel
{
   public boolean isCellEditable(int row, int col)
   {
       return col==0;
   }

   public Class getColumnClass(int col)
   {
      return col==0 ? Boolean.class : super.getColumnClass(col);
   }

}
0
 
LVL 92

Expert Comment

by:objects
ID: 10916074
you'll also need to add a setValueAt() method
0
 

Author Comment

by:Kennywen
ID: 10916084
how about the item listener?
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10916095
Add the checkbox component to the cell as given in the example
and add your listener to that.
0
 
LVL 30

Assisted Solution

by:mayankeagle
mayankeagle earned 25 total points
ID: 10916105
0
 
LVL 92

Assisted Solution

by:objects
objects earned 25 total points
ID: 10916107
instead of an itemlistener you would use a TableModelListener to listener for changes to table data.
0
 

Author Comment

by:Kennywen
ID: 10916184
currently i'm using boolean datatype to make the checkbox and i have a checkbox for the table header too.

Checkbox header is create by:
JTableHeader header = table.getTableHeader();  
header.addMouseListener(new ColumnHeaderListener());
MyItemListener myItemListener = new MyItemListener();
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      aColumn.setHeaderRenderer(new CheckBoxHeader(myItemListener));
      break;
}

when the user click on the checkbox on the header then i will set all the checkbox in the table to become checked. but when the user uncheck all the checkbox on the table then how can i uncheck the checkbox on the table header.

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 10916276
you need to define a header cell editor.
0
 

Author Comment

by:Kennywen
ID: 10916306
i think i can use :
table.getModel().addTableModelListener(new MyTableModelListener(table));
0
 
LVL 23

Assisted Solution

by:rama_krishna580
rama_krishna580 earned 25 total points
ID: 10916504
check this code..it will help you..

JTable table = new JTable();
   
    // Add data
   
    // Create text field and add action
    JTextField textField = new JTextField();
    textField.setAction(new UpdateAnchorAction(table));
   
    // Add selection listener to table
    SelectionListener listener = new SelectionListener(table, textField);
    table.getSelectionModel().addListSelectionListener(listener);
    table.getColumnModel().getSelectionModel()
        .addListSelectionListener(listener);
   
    // Add value changed listener to table
    table.getModel().addTableModelListener(new MyTableModelListener(table, textField));
   
    // Create a frame and add both components to the frame
    JFrame frame = new JFrame();
    frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    frame.getContentPane().add(textField, BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
   
    public class SelectionListener implements ListSelectionListener {
        JTable table;
        JTextField textField;
   
        // It is necessary to keep the table since it is not possible
        // to determine the table from the event's source
        SelectionListener(JTable table, JTextField textField) {
            this.table = table;
            this.textField = textField;
        }
   
        // Update the text field whenever the anchor cell changes
        public void valueChanged(ListSelectionEvent e) {
            int rowIndex = table.getSelectionModel().getAnchorSelectionIndex();
            int vColIndex = table.getColumnModel().getSelectionModel()
                .getAnchorSelectionIndex();
   
            // Get the value and set the text field
            textField.setText((String)table.getValueAt(rowIndex, vColIndex));
        }
    }
   
    public class MyTableModelListener implements TableModelListener {
        JTable table;
        JTextField textField;
   
        // It is necessary to keep the table since it is not possible
        // to determine the table from the event's source
        MyTableModelListener(JTable table, JTextField textField) {
            this.table = table;
            this.textField = textField;
        }
   
        // Update the text field whenever the value in the anchor cell changes
        public void tableChanged(TableModelEvent e) {
            // Get anchor cell location
            int rAnchor = table.getSelectionModel().getAnchorSelectionIndex();
            int vcAnchor = table.getColumnModel().getSelectionModel()
                .getAnchorSelectionIndex();
   
            // This method is defined in
            // e915 Converting a Column Index Between the View and Model in a JTable Component
            int mcAnchor = toModel(table, vcAnchor);
   
            // Get affected rows and columns
            int firstRow = e.getFirstRow();
            int lastRow = e.getLastRow();
            int mColIndex = e.getColumn();
   
            if (firstRow != TableModelEvent.HEADER_ROW
                    && rAnchor >= firstRow
                    && rAnchor <= lastRow
                    && (mColIndex == TableModelEvent.ALL_COLUMNS
                        || mColIndex == mcAnchor)) {
                // Set the text field with the new value
                textField.setText((String)table.getValueAt(rAnchor, vcAnchor));
            }
        }
    }
   
    public class UpdateAnchorAction extends AbstractAction {
        JTable table;
        UpdateAnchorAction(JTable table) {
            super("Set Anchor");
            this.table = table;
        }
   
        // Update the value in the anchor cell whenever the text field changes
        public void actionPerformed(ActionEvent evt) {
            JTextField textField = (JTextField)evt.getSource();
   
            // Get anchor cell location
            int rAnchor = table.getSelectionModel().getAnchorSelectionIndex();
            int vcAnchor = table.getColumnModel().getSelectionModel()
                .getAnchorSelectionIndex();
   
            table.setValueAt(textField.getText(), rAnchor, vcAnchor);
        }
    }


R.k
0
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10916514
The trick is to listen to the model of the table.

Table models fire events in the TableModelListener interface.

If you implement this interface, you can add a listener to the table model as follows:

  tableName.getModel().addTableModelListener(new MyTableModelListener());

all the best

R.K
0
 

Author Comment

by:Kennywen
ID: 10916620
my problem on the tableName.getModel().addTableModelListener(new MyTableModelListener()); is when i call customCheckbox.setSelected(false); the checkbox will not become uncheck but when i minimize and then maximize the window the checkbox will become uncheck. why?

JTableHeader header = table.getTableHeader();  
header.addMouseListener(new ColumnHeaderListener());
MyItemListener myItemListener = new MyItemListener();
table.getModel().addTableModelListener(new MyTableModelListener(table));
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
      customCheckbox = new CheckBoxHeader(myItemListener);
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      aColumn.setHeaderRenderer(customCheckbox);
      break;
}

thanks
0
 

Author Comment

by:Kennywen
ID: 10916763
do i need to refresh the table?
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10916792
For table data change..

((AbstractTableModel)table.getModel()).fireTableDataChanged();


For structure change of table

((AbstractTableModel)table.getModel()).fireTableStructureChanged() ;
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:Kennywen
ID: 10916813
just wonder why the customCheckbox.setSelected(false); will not set the checkbox to false.

public class CheckBoxHeader extends JCheckBox
0
 

Author Comment

by:Kennywen
ID: 10916843
can i just refresh the table header?

thanks
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10916860
You can't do that...
0
 

Author Comment

by:Kennywen
ID: 10916911
can anyone tell me why the customCheckbox.setSelected(false); will not uncheck the checkbox?

thanks
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10916955
Try calling the updateUI () method on the table.
0
 

Author Comment

by:Kennywen
ID: 10916970
>> customCheckbox.updateUI();

still the same.
0
 

Author Comment

by:Kennywen
ID: 10916975
the checkbox will become uncheck when i click on the table header.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10916985
I said: >> on the table.

table.updateUI () ;
0
 

Author Comment

by:Kennywen
ID: 10916998
how can i call the click table header function in my program?

thanks
0
 

Author Comment

by:Kennywen
ID: 10917006
Sorry,
>> table.updateUI () ;

also the same.
0
 

Author Comment

by:Kennywen
ID: 10917045
actually the checkbox is unchecked when i call customCheckbox.setSelected(false); the only problem is the tick graphic still in the checkbox. after i call customCheckbox.setSelected(false); the checkbox will become checked when i try to click on the checkbox. the only problem is the tick graphic....
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 25 total points
ID: 10917547
>> I have a table and i want to add the checkbox and checkbox listener at the left hand side. But how can i add it?

I created a demo app for you from scratch. It consists of three files

1) MyObject.java  (the object that contains the info of your table rows)

public class MyObject {
   
    private boolean bool = false; // default value
    private String field1 = ""; // default value
    private int field2 = 0; // default value

    public MyObject() {
    }

    public String getField1() { return field1; }
    public int getField2() { return field2; }
    public void setField1(String f1) { field1 = f1; }
    public void setField2(int f2) { field2 = f2; }
    public boolean getBool() { return bool; }
    public void setBool(boolean b) { bool = b; }
}

2) MyTableModel.java (the table model to use for your table):

import javax.swing.table.*;
import javax.swing.*;
import java.util.*;

public class MyTableModel extends DefaultTableModel {
   
    List data; // a list of MyObject's
   
    final String[] columnNames = { "my check box", "field 1", "field 2" };
   
    public MyTableModel(List d) {
        this.data = d;
    }

   public boolean isCellEditable(int row, int col) {
     return col==0;
   }

   public Class getColumnClass(int col) {
      return col==0 ? Boolean.class : super.getColumnClass(col);
   }
   
   public int getRowCount() {
       return data==null ? 0 : data.size();
   }
   
    public int getColumnCount() {
        return columnNames.length;
    }
   
    public Object getValueAt(int row, int col) {
        if ( row < 0 || row >= data.size() ) return null;
        MyObject myObj = (MyObject) data.get(row);
        if (col==0)
            return new Boolean(myObj.getBool());
        else if (col==1)
            return myObj.getField1();
        else if (col==2)
            return new Integer(myObj.getField2());
        else return null;
    }

    public void setValueAt(Object value, int row, int col) {
        if ( row < 0 || row >= data.size() || col!=0 ) return;
        // only col=0 is editable (in this example)
        MyObject myObj = (MyObject) data.get(row);
        myObj.setBool( ((Boolean)value).booleanValue() );
        if ( ((Boolean)value).booleanValue() )
            myObj.setField2(1000);
        else
            myObj.setField2(900);
        fireTableCellUpdated(row, col);
        fireTableCellUpdated(row, 2); // to see the field2 changes
    }
   
    public String getColumnName(int col) {
        return columnNames[col];
    }
}

3) TableDemo (the main app that shows how to use the above):

import java.util.*;
import javax.swing.*;

public class TableDemo extends javax.swing.JFrame {

    private JScrollPane jScrollPane1;
    private JTable theTable;
   
    public TableDemo() {
        initComponents();
        initTable();
    }
   
    private void initTable() {
        MyTableModel model = new MyTableModel(getTableData());
        theTable.setModel(model);
    }
   
    private List getTableData() {
        // For this example we generate the data (hardcoded)
        List data = new ArrayList();
        MyObject obj = new MyObject();
        obj.setField1("Field1 entry");
        data.add( obj );
        obj = new MyObject();
        obj.setField1("Field1 another entry");
        obj.setField2(15);
        data.add( obj );
        obj = new MyObject();
        obj.setField1("Field1 yet another");
        obj.setField2(45);
        data.add( obj );
        return data;
    }
   
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        theTable = new javax.swing.JTable();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jScrollPane1.setViewportView(theTable);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
   
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) {
            System.exit(0);
        }
       
        new TableDemo().show();
    }
}

When you run this demo you will be able to check/uncheck the check boxes in the 1st column.
When you check them, you'll see that field2 becomes 1000. When you uncheck field2 becomes 900.
(Weird behaviour but hey, it's to demo ;)
0
 
LVL 92

Expert Comment

by:objects
ID: 10923122
That TableModel looks familiar :)
0
 

Author Comment

by:Kennywen
ID: 10924459
i get my solution by repaint the panel........
0
 
LVL 92

Expert Comment

by:objects
ID: 10924582
:)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10925788
Thanks for accepting
0
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10983431
best of luck..

R.K

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Java 1603 Error 2 42
mergeTwo  challenge 13 72
java set up 1 46
backtracking recursion  code 19 40
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now