Solved

JTable

Posted on 2001-06-21
4
629 Views
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.
0
Comment
Question by:vnd
4 Comments
 
LVL 2

Expert Comment

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

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

      if (isSelected) {
         ((JButton)value).setForeground(
          table.getSelectionForeground()); //modify this to do what you intend to do when the burron is clicked
         ((JButton)value).setBackground(
          table.getSelectionBackground());  //modify this to do what you intend to do when the burron is clicked
      } else {
         ((JButton)value).setForeground(table.getForeground());
         ((JButton)value).setBackground(table.getBackground());
      }
      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:
  table.setDefaultRenderer(
     JButton.class, new CustomButtonRenderer());

Hope this helps,
Padma.
0
 
LVL 9

Accepted Solution

by:
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() {
            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
 
LVL 1

Expert Comment

by:Moondancer
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.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process for further information, if needed.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

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.
http://www.experts-exchange.com/questions/Q.11822919.html
http://www.experts-exchange.com/questions/Q.11826698.html
http://www.experts-exchange.com/questions/Q.20096286.html
http://www.experts-exchange.com/questions/Q.20102331.html
http://www.experts-exchange.com/questions/Q.20102235.html
http://www.experts-exchange.com/questions/Q.20103717.html
http://www.experts-exchange.com/questions/Q.20110717.html
http://www.experts-exchange.com/questions/Q.20131726.html
http://www.experts-exchange.com/questions/Q.20136436.html
http://www.experts-exchange.com/questions/Q.20143119.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
http://www.experts-exchange.com/questions/Q.20124950.html
http://www.experts-exchange.com/questions/Q.20139578.html

PLEASE DO NOT AWARD THE POINTS TO ME.  
 
------------>  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 http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643

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.
 
Moondancer
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.
0
 
LVL 5

Expert Comment

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.

707 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

12 Experts available now in Live!

Get 1:1 Help Now