Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

JCheckBox in JTable

Posted on 2001-09-04
7
Medium Priority
?
666 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 400 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses

636 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