Solved

JCheckBox in JTable

Posted on 2001-09-04
7
641 Views
Last Modified: 2008-02-01

How can I put JCheckBox i all cells i the 3rd colum, in a JTable?


import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class TableDisplay extends JFrame
{
     
     private JTable table;
   
     public TableDisplay()
     {    
      setSize(400, 400);
           
         table = new JTable(3,4);
         JScrollPane scroller = new JScrollPane( table );
         getContentPane().add(scroller);  
            show();
       }

        public static void main( String args[] )
        {
         final TableDisplay app = new TableDisplay();

          app.addWindowListener(new WindowAdapter()
           {
          public void windowClosing(WindowEvent e  )
            {  
             
                System.exit( 0 );
            }
           }
           );

  }
}
0
Comment
Question by:Saxo
7 Comments
 
LVL 16

Expert Comment

by:heyhey_
Comment Utility
afair you can find some sample code in the SwingSet demo (check jdk demos subdirectory)
0
 
LVL 1

Expert Comment

by:boazbl1
Comment Utility
JTable uses TableModel to hold data.
you can implemet your own TableModel interface, or extend the AbstractTableModel or DefaultTableModel, and override the method

public Class getColumnClass(int column){
  if (column == 2) // the 3rd column
      return Boolean.class;
  else
      return super.getColumnClass(column);
}
0
 
LVL 9

Accepted Solution

by:
Ovi earned 100 total points
Comment Utility
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TableEditors extends JFrame {
      private SmartTable table;
      private SmartTableModel model;
      
      public TableEditors() {
            init();
      }
      
      private void init() {
            getContentPane().setLayout(new BorderLayout());
            setSize(400, 300);
            setLocation(300, 100);
            table = new SmartTable();
            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
            setVisible(true);
      }
      
      class SmartTable extends JTable {
   
            public SmartTable() {
                  model = new SmartTableModel();
                  setModel(model);
                  createColumns();
                  setForeground(Color.red);
                  setBackground(new Color(255, 239, 185));
                  setGridColor(Color.orange);
                  setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
     
     
      setRowHeight(35);
                  setSelectedRow(0);
                  setSelectedCol(0);
            }
            
            protected void createColumns() {
                  for(int i = 0; i<model.getColumnCount(); i++) {
                        TableColumn column = getColumn(model.getColumnName(i));
        column.setCellRenderer(new GenericRenderer());
        column.setCellEditor(new GenericEditor());
                  }
            }
   
            public void setSelectedRow(int row) {
                  if(row == -1)
                        return;
                  else {
                        setRowSelectionInterval(row, row);
                  }
            }
            
            public void setSelectedCol(int col) {
                  if(col == -1)
                        return;
                  else {
                        setColumnSelectionInterval(col, col);
                  }
            }
            
      }
 
      class SmartTableModel extends AbstractTableModel {
            protected ColumnDescriptor cols[] =  {
                  new ColumnDescriptor("Field1", 40, JLabel.LEFT),
                  new ColumnDescriptor("Field2", 50, JLabel.LEFT),
                  new ColumnDescriptor("Field3", 100, JLabel.LEFT),
            };
            protected Vector dObjects;

            public SmartTableModel() {
                  dObjects = new Vector();
      initModelData();
            }
   
    public void initModelData() {
          Object[] row = new Object[3];
      row[0] = "string"; row[1] = "string"; row[2] = "string";
      dObjects.addElement(row);
     
      row = new Object[3];
      row[0] = "string"; row[1] = "string"; row[2] = new JButton("button");
      dObjects.addElement(row);

      row = new Object[3];
      row[0] = "string"; row[1] = new JButton("button"); row[2] = "string";
      dObjects.addElement(row);

          row = new Object[3];
          row[0] = "string"; row[1] = new JButton("button"); row[2] = new JCheckBox("checkbox");
          dObjects.addElement(row);
     
          row = new Object[3];
          row[0] = new JButton("button");row[1] = new JCheckBox("checkbox");row[2] = "string";
          dObjects.addElement(row);
     
          row = new Object[3];
          row[0] = new JButton("button");row[1] = new JCheckBox("checkbox");row[2] = new JButton("button");
          dObjects.addElement(row);
          updateObjects();
    }

            protected void updateObjects() { fireTableDataChanged(); }
            public int getColumnCount() {      return(cols.length); }
            public int getRowCount() { return(dObjects.size());      }
            public String getColumnName(int c) { return(cols[c].name); }
            public boolean isCellEditable(int row, int col) {
          return((getObjectAt(row, col) instanceof String)?false:true);
    }
   
    public Object getObjectAt(int row, int col)  {
          return(((Object[]) dObjects.elementAt(row))[col]);
    }
   
            public Object getValueAt(int row, int col) {
                  if(getRowCount() <= 0)
                        return "";
                  if(row<0||row>=getRowCount())
                        return "";
      Object cellData = ((Object[]) dObjects.elementAt(row))[col];
      return(cellData);
            }
      }
 
      class ColumnDescriptor {
        public String name;
        public int width;
        public int alignment;
        
        public ColumnDescriptor(String n, int w, int a) {
          name = n;
          width = w;
          alignment = a;
        }
      }
      
  class GenericRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int col) {
          Object o = model.getObjectAt(row, col);
      if(o instanceof JButton || o instanceof JCheckBox) {
            if(o instanceof JCheckBox)
                  ((Component) o).setBackground(table.getBackground());
            return((Component) o);
      }
      Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
      return(c);  
        }
  }
 
  class GenericEditor extends DefaultCellEditor {
        JTable tbl;
        private int lastRow = 0;
        private int lastCol = 0;
    private Object editor;
   
        public GenericEditor() {
      super(new JCheckBox());
        }
        public Component getTableCellEditorComponent(JTable t, Object v, boolean sel, int r, int c) {
          tbl = t;
      lastRow = r;
      lastCol = c;
          Object o = model.getObjectAt(r, c);
      editor = o;
      if(o instanceof JButton || o instanceof JCheckBox)
            return((Component) o);
      editor = new JTextField(v.toString());  
      return((Component) editor);
    }
   
        public Object getCellEditorValue() {
      return(model.getObjectAt(lastRow, lastCol));
    }
        public boolean isCellEditable(java.util.EventObject ev) {      return(true); }
        public boolean shouldSelectCell(java.util.EventObject ev) {      return(false); }
        public boolean stopCellEditing() {
              tbl.editingStopped(new ChangeEvent(this));
          return(true);
    }
        public void cancelCellEditing() {}
        public void addCellEditorListener(CellEditorListener cel) {}
        public void removeCellEditorListener(CellEditorListener cel) {}
  }
 
      public static void main(String[] args) {
            TableEditors t = new TableEditors();      
      }
      
}
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 9

Expert Comment

by:Ovi
Comment Utility
Compile and runn'it
0
 
LVL 1

Expert Comment

by:boazbl1
Comment Utility
well, Ovi's proposed answer looks good, and is very generic, but the question was how to use JCheckBox, so the simplest way is to return Boolean.class by the TableModel.
0
 
LVL 9

Expert Comment

by:Ovi
Comment Utility
You have right of course, I just give a general solution and a general example in the usage of some cell editors and renderers, so the user can learn more things from a simple question.
0
 

Author Comment

by:Saxo
Comment Utility

Thank you Ovi. I can use it.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

771 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

10 Experts available now in Live!

Get 1:1 Help Now