Posted on 2001-06-21
Last Modified: 2010-04-16
hi i need to place a JButton into Jtable. How would i do that ? Do i must overide a default cellRenderer that it uses in order to get the effect ? I only need buttons in one column. Just point me to direction thanks.
Question by:vnd

Expert Comment

ID: 6215905
This code example uses a JButton as the renderer cell.

class CustomButtonRenderer extends JButton
          implements TableCellRenderer {
   public CustomButtonRenderer() {
   public Component getTableCellRendererComponent(
                      JTable table, Object value,
                      boolean isSelected,
                      boolean hasFocus, int row,
                      int column) {

      if (isSelected) {
          table.getSelectionForeground()); //modify this to do what you intend to do when the burron is clicked
          table.getSelectionBackground());  //modify this to do what you intend to do when the burron is clicked
      } else {
      return (JButton)value;

Here, for the sake of an example, selection of the cell toggles the button colors. Ofcourse you can replace these lines to do what you intend to do when the button is being clicked.

Alternately, all JButton components can be configured to use the CustomButtonRenderer in the table with a call to setDefaultRenderer as follows:
     JButton.class, new CustomButtonRenderer());

Hope this helps,

Accepted Solution

Ovi earned 100 total points
ID: 6217134
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() {
      private void init() {
            getContentPane().setLayout(new BorderLayout());
            setSize(400, 300);
            setLocation(300, 100);
            table = new SmartTable();
            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
      class SmartTable extends JTable {
            public SmartTable() {
                  model = new SmartTableModel();
                  setBackground(new Color(255, 239, 185));
            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)
                  else {
                        setRowSelectionInterval(row, row);
            public void setSelectedCol(int col) {
                  if(col == -1)
                  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();
    public void initModelData() {
          Object[] row = new Object[3];
      row[0] = "string"; row[1] = "string"; row[2] = "string";
      row = new Object[3];
      row[0] = "string"; row[1] = "string"; row[2] = new JButton("button");

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

          row = new Object[3];
          row[0] = "string"; row[1] = new JButton("button"); row[2] = new JCheckBox("checkbox");
          row = new Object[3];
          row[0] = new JButton("button");row[1] = new JCheckBox("checkbox");row[2] = "string";
          row = new Object[3];
          row[0] = new JButton("button");row[1] = new JCheckBox("checkbox");row[2] = new JButton("button");

            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 "";
                        return "";
      Object cellData = ((Object[]) dObjects.elementAt(row))[col];
      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);
  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));
        public void cancelCellEditing() {}
        public void addCellEditorListener(CellEditorListener cel) {}
        public void removeCellEditorListener(CellEditorListener cel) {}
      public static void main(String[] args) {
            TableEditors t = new TableEditors();      

Expert Comment

ID: 6900207
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> You cannot delete a question with comments, special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process for further information, if needed.

Click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.  Anytime you have questions which are LOCKED with a Proposed Answer but does not serve your needs, please reject it and add comments as to why.  In addition, when you do grade the question, if the grade is less than an A, please add a comment as to why.  This helps all involved, as well as future persons who may access this item in the future to seek help.

To view your open questions, please click the following link(s) and keep them all current with updates.

To view your locked questions, please click the following link(s) and evaluate the proposed answer.

------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link

Moderators will finalize this question if still open in 7 days, by either moving this to the PAQ (Previously Asked Questions) at zero points, deleting it or awarding expert(s) when recommendations are made, or an independent determination can be made.  Expert input is always appreciated to determine the fair outcome.
Thank you everyone.
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.

Expert Comment

ID: 6995198
Admin notified of User neglect. Force-accepted by
CS Moderator

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying 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
print map entry 34 72
MySqlDump not dumping triggers 1 43
Desingning Refactoring existing code 2 26
junit as external jar or library 7 24
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

830 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