Solved

JTable and Cells With Buttons

Posted on 2001-06-10
13
655 Views
Last Modified: 2010-08-05
Hello People

I want to use a JTable to use some data. However, I want to use Buttons in some cells( that would perform some action to change some contents).
I was wondering if someone has some examples or some ideas about how to perform this task.

Also when we use Objects with "Yes" or "No" contents the cells are displayed with check boxes. But that makes the whole column with these check boxes. I was wondering is this possible that only some cells of the table do this conversion and others just show the text.
I mean is this possible to make each cells rendering different from all the other cells.




0
Comment
Question by:StyloHere
  • 6
  • 2
  • 2
  • +3
13 Comments
 

Author Comment

by:StyloHere
ID: 6175346
I am really in trouble. Any Suggestions woudl be appreciated.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6175840
<<Listening>>
0
 
LVL 5

Expert Comment

by:Calron
ID: 6175914
You will have to write your own cell renderers and cell editors. Have a look at the java tutorial:

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

there the concept is introduced and you can take it from there.
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 9

Expert Comment

by:Ovi
ID: 6177063
1. Create your own cell editor.
2. In the table model return the class of the cell according to the data you have in it.

If you wait I will write you some code for that.
0
 

Author Comment

by:StyloHere
ID: 6177269
Thanks a lot everybody

(just Curious) Mr. Sudhakar what are you listening to - Bhangra?

Okay Ovi, Thanks once again and I think that would be great.
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6178403
Hi,

Check out this PAQ:
www.experts-exchange.com/jsp/qShow.jsp?ta=java&qid=11427278#1

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6178413

BTW, note to 'listeners': There is 'Subscribe' button below comment--you can get notifications without comment posting. Thanks to EE engineering team!

0
 
LVL 9

Expert Comment

by:Ovi
ID: 6181093
Okay, I've writed to you some code but because of time frame very short that I have is not fuklly functional. The table in the example is curently suporting different renderers and editors for every cell (default - string, Button, JCheckBox). The actual problem not solved is the saving of the edited value and ActionListener not suported. You can add manually to each JButton on the table listeners and do what you wat in it. ... but as a starting point I think is a good example, which follows your specifications (cell buttons, cell checkboxes, all of that at the level of cells and not columns). For more features in the implementation you must wait again (sorry for that), or maybewill not be so paintful for you to give a try yourself (as you wish).


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(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];
      if(cellData instanceof JButton)
            return(((JButton) cellData).getText());
                  if(cellData instanceof JCheckBox)
                        return(((JCheckBox) cellData).getText());
      return(cellData.toString());  
            }
      }
 
      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)
            return(new ButtonRenderer(value.toString()));
              if(o instanceof JCheckBox)
                    return(new CheckBoxRenderer(value.toString()));
      return(super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col));  
        }
  }
 
  class ButtonRenderer extends JPanel implements TableCellRenderer {
        private JButton button;
   
    public ButtonRenderer(String lbl) {
          super();
      button = new JButton(lbl);
      setBackground(table.getBackground());
          add(button, BorderLayout.CENTER);
    }
        
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int col) {
          String v = value.toString();
      button.setText(v);
      return(button);
    }
   
    public JButton getButton() {
          return(button);
    }
   
    public void addActionListener(ActionListener al) {
          button.addActionListener(al);
    }
   
        public void removeActionListener(ActionListener al) {
              button.removeActionListener(al);
        }
  }
 
  class CheckBoxRenderer extends JPanel implements TableCellRenderer {
        private JCheckBox check;
   
    public CheckBoxRenderer(String lbl) {
          super();
          setBackground(table.getBackground());
      check = new JCheckBox(lbl);
          check.setBackground(table.getBackground());
          add(check, BorderLayout.CENTER);
    }
        
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int col) {
          String v = value.toString();
      check.setText(v);
      return(check);
    }
   
    public JCheckBox getCheck() {
          return(check);
    }
   
    public void addActionListener(ActionListener al) {
          check.addActionListener(al);
    }
   
    public void removeActionListener(ActionListener al) {
          check.removeActionListener(al);
    }
  }
 
  class GenericEditor implements TableCellEditor {
        JTable tbl;
        private int lastRow = 0;
        private int lastCol = 0;
   
        public GenericEditor() {
        }
        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);
      if(o instanceof JButton)
            return(new ButtonRenderer(v.toString()).getButton());
          if(o instanceof JCheckBox)
                return(new CheckBoxRenderer(v.toString()).getCheck());
      return(new JTextField(v.toString()));  
    }
   
        public Object getCellEditorValue() {
          Object o = model.getObjectAt(lastRow, lastCol);
      return(o);
    }
        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
 
LVL 9

Expert Comment

by:Ovi
ID: 6181107
Sorry about : "is not fuklly functional.", I mean "is not fully functional." :-)
Cheers
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6181344
.. or a simplifyed one :




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(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];
      if(cellData instanceof JButton)
            return(((JButton) cellData).getText());
                  if(cellData instanceof JCheckBox)
                        return(((JCheckBox) cellData).getText());
      return(cellData.toString());  
            }
      }
 
      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) {
        JButton b = new JButton(value.toString());
        return(b);
      }
              if(o instanceof JCheckBox) {
                JCheckBox c = new JCheckBox(value.toString());
                c.setBackground(table.getBackground());
                return(c);                
              }
      return(super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col));  
        }
  }
 
  class GenericEditor extends DefaultCellEditor {
        JTable tbl;
        private int lastRow = 0;
        private int lastCol = 0;
   
        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);
      if(o instanceof JButton || o instanceof JCheckBox)
            return((Component) o);
      return(new JTextField(v.toString()));
    }
   
        public Object getCellEditorValue() {
          Object o = model.getObjectAt(lastRow, lastCol);
      return(o);
    }
        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
 
LVL 9

Accepted Solution

by:
Ovi earned 200 total points
ID: 6184607
Final Version


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();      
      }
      
}


Cheers.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6205133
Yo man, are you still there ?
0
 

Expert Comment

by:SpideyMod
ID: 8289466
Force Accepted

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jar file executable 12 58
javap not working 8 58
pagenation logic how it is working in my code 1 53
Java 8 to Java 6 8 20
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
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…
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 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:

839 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