Solved

JCheckBox in JTable

Posted on 2001-09-04
7
660 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 16

Expert Comment

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

Expert Comment

by:boazbl1
ID: 6452727
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
ID: 6452755
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:Ovi
ID: 6452758
Compile and runn'it
0
 
LVL 1

Expert Comment

by:boazbl1
ID: 6452768
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
ID: 6452783
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
ID: 6452886

Thank you Ovi. I can use it.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jdbc error in jsp application 20 86
jmss example java 2 46
IBM TS2900 (3572) Tape Autoloader Java? 12 101
Firefox and firebub 5 22
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

738 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