Adding JButton into JTable cells

Hi there!!
I want to add a JButton into JTable cells.In fact I have got two classes.Class2 has been extended from the AbstractTableModel class and Class1 which is using Class2's model,,,here's the code,,
Class1
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Class1 extends javax.swing.JFrame {
   //////GUI specifications
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestTableButton().setVisible(true);
        Class2 model=new Class2();
        jTable1=new JTable(model);
        jScrollPane1.setViewportView(jTable1);
    // Variables declaration - do not modify                    
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                  
    private javax.swing.JTable jTable1;
}Class2
import javax.swing.table.*;
public class Class2 extends AbstractTableModel{
    private String[] columnNames = {"A","B","C"};
    private Object[][] data = {
    public int getColumnCount() {
        return columnNames.length;
    public int getRowCount() {
        return data.length;
    public String getColumnName(int col) {
        return columnNames[col];
    public Object getValueAt(int row, int col) {
        return data[row][col];
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
     * Don't need to implement this method unless your table's
     * editable.
    public boolean isCellEditable(int row, int col) {
        //Note that the data/cell address is constant,
        //no matter where the cell appears onscreen.
            return false;
     * Don't need to implement this method unless your table's
     * data can change.
    public void setValueAt(Object value, int row, int col) {
        data[row][col] = value;
        fireTableCellUpdated(row, col);
}what modifications shud I be making to the Class2 calss to add buttons to it?
Can anybody help plz,,,,,??
Thanks in advance..

Hi rebol!
I did search out a lot for this but I found my problem was a bit different,,in fact I want to use another class's model into a class being extended by JFrame,,so was a bit confused,,,hope you can give me some ideas about how to handle that scenario,,I know this topic has been discussed before here many a times and also have visited this link,,
http://forum.java.sun.com/thread.jspa?threadID=465286&messageID=2147913
but am not able to map it to my need,,,hope you can help me a bit...
Thanks .....

Similar Messages

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • Adding JButtons to JTable

    Hello all,
    How can I add JButtons to a JTable?
    I found an article that is supposed to show you how to do just that:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I downloaded the code in the article and it works to an extent - I can see the buttons in the table but the buttons seem as if they are disabled :( Since I used this code in my application, I get the same behavior too.
    Is there a bug in the code? Is there a simpler solution? What am I missing?
    Raj

    Thanks. That makes the button clickable. But now the button changes back to it's old value when you click on another cell. I suppose that's because we have 2 buttons, one for rendering and one for editing. So I added a setValueAt(Object value, int row, int column) to MyModel. This works throws class cast exception.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class ButtonInTable extends JFrame {
        JTable t=new JTable(new MyModel());
        public ButtonInTable() {
            this.getContentPane().add(new JScrollPane(t));
            this.setBounds(50,50,300,200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            t.setDefaultEditor(Object.class,new ButtonEditor());
            t.setDefaultRenderer(Object.class,new ButtonRenderer());      
        public static void main(String[] args) {
            ButtonInTable buttonInTable1 = new ButtonInTable();
            buttonInTable1.show();
        class ButtonEditor extends JButton implements TableCellEditor {
            Object currentValue;
            Vector listeners=new Vector();
            public ButtonEditor() {
                            this.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    currentValue=JOptionPane.showInputDialog("Input new value!");
                                    if (currentValue!=null) {
                                        setText(currentValue.toString());
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                currentValue=value;
    //            this.setText(value.toString());
                this.setText( ((JButton)value).getText() );
                return this;
            public Object getCellEditorValue() {
                return currentValue;
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingStopped(ce);
                return true;
            public void cancelCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingCanceled(ce);
            public void addCellEditorListener(CellEditorListener l) {
                listeners.add(l);
            public void removeCellEditorListener(CellEditorListener l) {
                listeners.remove(l);
        class ButtonRenderer extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent
                    (JTable table, Object button, boolean isSelected, boolean hasFocus, int row, int column) {
                return (JButton)button;
        class OldModel extends DefaultTableModel {
            public OldModel() {
                super(new String[][]{{"1","2"},{"3","4"}},new String[] {"1","2"});
        class MyModel extends AbstractTableModel {
            private String[] titles = { "A", "B" };
            private Object[][] summaryTable =
                    { new JButton("11"), new JButton("12") },
                    { new JButton("21"), new JButton("22") }
            public MyModel(){
                super();
            public int getColumnCount() {
                return titles.length;
            public String getColumnName(int col) {
                return titles[col];
            public int getRowCount() {
                return summaryTable.length;
            public Object getValueAt(int row, int col) {
                return summaryTable[row][col];
            public void setValueAt(Object value, int row, int column) {
                summaryTable[row][column] = value;
                fireTableCellUpdated(row, column);
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                return true;
    }

  • Adding JCheckBox into JTable

    Hi all,
    I added a JCheckBox into a JTable, while clicking the check box the selection will not replicate into the JTable. Please help me to resolve this issue.
    * TableDemo.java
    * Created on September 5, 2006, 11:49 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package simPackage;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    * @author aathirai
    public class TableDemo extends JPanel{
       // public JRadioButton[] dataButton;
        /** Creates a new instance of TableDemo */
        public TableDemo() {
            JCheckBox firstCheck = new JCheckBox("");
            Object[][] data={{firstCheck,"2","4","5","2"}};
                    String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
                    JTable searchResultTable = new JTable(data,columnNames);
                    searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
                    searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
            JScrollPane scrollPane = new JScrollPane(searchResultTable);
            //Add the scroll pane to this panel.
            add(scrollPane);
    public static void main(String args[])   {
         JFrame jFrame  = new JFrame("testing");
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableDemo newContentPane = new TableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            jFrame.setContentPane(newContentPane);
            //Display the window.
            jFrame.pack();
            jFrame.setVisible(true);
    class RadioButtonRenderer implements TableCellRenderer {
        public JCheckBox check1 = new JCheckBox("");
      public Component getTableCellRendererComponent(JTable table, Object value,
       boolean isSelected, boolean hasFocus, int row, int column) {
          check1.setBackground(Color.WHITE);
         return check1;
    class RadioButtonEditor extends DefaultCellEditor{
        public JCheckBox check1 = new JCheckBox("");
      boolean state;
      int r, c;
      JTable t;
      class RbListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          if (e.getSource() == check1){
            state = true;
          else{
            state = false;
          RadioButtonEditor.this.fireEditingStopped();
      public RadioButtonEditor(JCheckBox checkBox) {
        super(checkBox);
      public Component getTableCellEditorComponent(JTable table, Object value,
       boolean isSelected, int row, int column) {
        RbListener rb = new RbListener();
        t = table;
        r = row;
        c = column;
        if (value == null){
          return null;
        check1.addActionListener(rb);
         //check1.setSelected(((Boolean)value).booleanValue());
        /*if (((Boolean)value).booleanValue() == true){
          check1.setSelected(true);
        return check1;
      public Object getCellEditorValue() {
        if (check1.isSelected() == true){
          return Boolean.valueOf(true);
        else{
          return Boolean.valueOf(false);
    }Thanks in advance.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class TableDemo extends JPanel
      public TableDemo()
        //JCheckBox firstCheck = new JCheckBox("");
        //Object[][] data={{firstCheck,"2","4","5","2"}};
        Object[][] data={{new Boolean(false),"2","4","5","2"}};
        String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
        JTable searchResultTable = new JTable(data,columnNames);
        //searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
        //searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
        TableColumn tc = searchResultTable.getColumnModel().getColumn(0);
        tc.setCellEditor(searchResultTable.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(searchResultTable.getDefaultRenderer(Boolean.class));
        JScrollPane scrollPane = new JScrollPane(searchResultTable);
        add(scrollPane);
      public static void main(String args[])
        JFrame jFrame  = new JFrame("testing");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        jFrame.setContentPane(newContentPane);
        jFrame.pack();
        jFrame.setVisible(true);
    }

  • Problem in adding image in jtable cells

    hi all.
    im creating a swing application using netbeans 6.0.
    i want to display image in cells of one column.
    for that i set an "image icon" directly to that cell in the "default table model", in that case it is displaying the path of that image in that cell!
    then i created a new label, and set the image as icon of that label. added that label in that cell. in this case it is printing label.tostring() to that cell!!
    please help.
    thanks in advance.

    You need to override getColumnClass to return Icon.class for the column containing the icon. A code snippet that demonstrates how you might do this:      table = new JTable (new DefaultTableModel (data, colNames) {
             public Class getColumnClass (int columnIndex) {
                switch (columnIndex) {
                   case 0: return Calendar.class;
                   case 1: return String.class;
                   case 2: return Icon.class;
                   //case 2: return Boolean.class;
                return null;
          });luck, db

  • Placing JButtons in JTable cells

    I would like to place JButtons in one column of a JTable.
    Can anyone post or point me toward some example code that illustrates this?
    Many thanks in advance.

    did you try this with the cell renderer
    This should work. Try extending the DefaultCellRenderer and set them as a jbutton
    hope this will work

  • JLabels into JTable cell

    Hi friends!
    I need to have a JTable with multiple JLabels inside its cells. I wrote a class wich implements TableCellRenderer the code is the following:
    public class JLabelCellRender extends JPanel implements  TableCellRenderer {
        Vector ObJLabelsV=new Vector();
        JLabel teste;
        public JLabelCellRender() {
            super();
        public java.awt.Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row, int column) {
            Vector labels=(Vector)value;
           for(int i=0;i<labels.size();i++) {
            add((JLabel)labels.elementAt(i));
            return this;
    }I nedd each cell having a variable number of JLabels, to do this I use a Vector.
    But I need to insert and remove JLabels in the main class. Like using the method setValueAt(ob,row,col) wich modifys the text in the cell I want to modify the text and the number of JLabels.
    The problem is I don't know how to insert and remove JLabels in the cells.
    I ask if I have to re-implement the setValueAt and getValueAt methods..
    Thanks in advance for help.
    Sory for my english.:)

    You need to do something similar to this
    public class JLabelCellRender extends JPanel implements  TableCellRenderer {
        Vector ObJLabelsV=new Vector();
        JLabel teste;
        public JLabelCellRender() {
            super();
        public java.awt.Component getTableCellRendererComponent(JTable table,  Object value, boolean isSelected,
                boolean hasFocus,  int row, int column) {
           // clear all exiting items in the panel
           removeAll();
           // obtain the new information for the
            Vector labels=(Vector)value;
           for(int i=0; i < labels.size(); i++) {
            add((JLabel)labels.elementAt(i));
           // adjust the row height of the current row to display all the labels
           table.setRowHeight(row, getPreferredSize().height);
            return this;
    }Now you just need to ensure that number of labels are different for the different cells you need to display.
    ICE

  • Adding checkbox to JTable cell

    Hi, I am tryin to add a checkbox to JTabel cell.
    But somehow i am ending up getting 'false' in the cell instead of checkbox.
    Can anyone please help me.
    here is my getColumnClass and getValuAt
    public Class getColumnClass(int column)
    { if(column==0) return Boolean.class;
         else return Object.class;
    public Object getValueAt(int nRow, int nCol) {
         if(nCol==0)
              return new Boolean(ch.isSelected());
    }

    You can use a cell rederer that will give you more flexibility .
    Add the renderer to a specific column and that will do the job.
    Here is the example:
    public class CheckBoxRenderer extends JCheckBox implements  TableCellRenderer {
        public CheckBoxRenderer() {
            super();
        public Component getTableCellRendererComponent(JTable table, java.lang.Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            Color c = table.getBackground();
            this.setBackground(c);
            setSelected(value != null && ((Boolean) value).booleanValue());
            return this;
    }In order to edit the value in a check box you will need to write a cell editor which
    is going to be easy.

  • Adding JPopupMenu to JTable cell

    Hi,
    I am just wondering if I can add a JPopup menu to each cell in a JTable, so that a user can perform some tasks.For example , a user should be able to delete a table cell by choosing the delete menu item in the popup menu
    many thanks
    Ramesh

    Hi,
    Add JPopupmenu and add JMenuItems on that according to your requirement. Add MouseListener to your table and on mouseReleased event check whether you have clicked the right mouse. If right mouse is clicked, then show the popup menu that you have already created. I think the following code will help you.
    JPopupMenu lJPopupMenu = new JPopupMenu();
    JMenuItem lJMenuItem1 = new lJMenuItem();
    lJPopupMenu.add(lJMenuItem1);
    lJTable.addMouseListener(this);
    MouseReleased(java.awt.event.MouseEvent mouseEvent) {
    if(mouseEvent.isPopupTrigger()){
    lJPopupMenu.show(lJTable, mouseEvent.getX(), mouseEvent.getY());
    ActionPerformed of the JMenuItem, you write the code based on the requirement.

  • Adding JTree to JTable cell is not expanding??

    Hi experts
    My problem is that as Tree expands, my table cell should expands accordingly.
    How do I do that??I do n't mind if other cells get expands.
    Please help me...?
    Thanks in advance

    How do I do that no such method is available.can you guide me or give me some code.I need urgently..
    Thank you very much

  • JButton in table cell in Find Mode

    Hello!
    I have JButton in JTable cell for calling LOV.
    When form goes to Find Mode all JButtons become disabled.
    Accordingly, I want that buttons active. Any help will be appreciated %)

    If the button is bound with an LOV Button binding, then I believe the framework checks the queryable property of the "target" attribute. Make sure that attribute has the "queryable" property checked in the View/Entity.
    Hope this helps.
    Erik

  • JButton "sticking" in a JTable Cell

    So I've modified the renderer and what not and slapped a button into a JTable Cell. The assignment requires it to turn red/green altrenativly when pressed. It works perfectly aside from the fact that the buttons appear to not "bounce back" when they switch colors. (i.e. They appear depressed when red and pressed when green). The code is below. any ideas?
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JButton;
    public class ButtonTableModel extends AbstractTableModel {
         private static final long serialVersionUID = 1;
         private Object[][] rows = new Object[2][1];
         private String[] columns = new String[1];
         public ButtonTableModel() {
              for(int k = 0; k < rows.length; k++) {
                   JButton button3 = new JButton("222");
                   button3.setSize(200, 200);
                   button3.setBackground(Color.red);
                   button3.addMouseListener(new ColorChanger(button3));
                   rows[k][0] = button3;
              /*button = new JButton("Test Button");
              button.setBackground(Color.red);
              button.addMouseListener(new ColorChanger(button));
              button2 = new JButton("asdf");
              button2.setBackground(Color.red);
              button2.addMouseListener(new ColorChanger(button2));
              rows[0][0] = button;
              rows[1][0] = button2;*/
         private class ColorChanger implements MouseListener {
              private JButton callingButton; //Stores the button that added the Listener
              public ColorChanger(JButton pCallingButton) {  //Constructs a ColorChanger that stores a given JButton
                   callingButton = pCallingButton;
              public void mouseClicked(MouseEvent e) { //When callingButton is clicked, its color changes alternativly to green/red
                   if(isGreen(callingButton) == false)
                        callingButton.setBackground(Color.green);
                   else
                        callingButton.setBackground(Color.red);
              //The 4 methods below are unused leftovers specified by the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         private boolean isGreen(JButton pButton) { //Returns true if a button's background is green, false otherwise
              if(pButton.getBackground() == Color.green)
                   return true;
              return false;
         public int getColumnCount() { //Returns the number of Columns in a table
              return columns.length;
         public int getRowCount() { //Returns the number of rows in the table
              return rows.length;
         public String getColumnName(int pCollumnIndex) { //Returns the name of the collumn
              return columns[pCollumnIndex];
         public Object getValueAt(int pRow, int pColumn) { //Returns the value at given table coordinates
              return rows[pRow][pColumn];
         public boolean isCellEditable(int pRow, int pColumn) { //Returns true if a cell at given coordinates is editable, false otherwise
                  return false;
         public Class getColumnClass(int pColumnIndex) { //Retrieves the class of the objects in a column
              return getValueAt(0, pColumnIndex).getClass();
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JTable;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.table.TableCellRenderer;
    public class JButtonJTableTest extends JFrame {
         private static final long serialVersionUID = 1;
         private JTable table;
         private TableCellRenderer tableCellRenderer;
         private MouseEvent e2;
         private Class columnClass;
         private JButton button;
         private Point mousePos;
         private int mouseRow, mouseColumn;
         public JButtonJTableTest() {
              super("JButton Table Test");
              table = new JTable(); //Setup the table, assigning the new renderer and model
              tableCellRenderer = table.getDefaultRenderer(JButton.class);
              table.setDefaultRenderer(JButton.class, new JButtonRenderer(tableCellRenderer));
              table.setModel(new ButtonTableModel());
              table.setGridColor(Color.blue);
              table.addMouseListener(new MouseForwarder());
              table.setShowGrid(true);
              add(table); //Add the table to the content pane
         private class MouseForwarder implements MouseListener {
              public void mouseClicked(MouseEvent e) {
                   mousePos = new Point(e.getX(), e.getY()); //Assing mouse coordinates to a point data structure
                   mouseRow = table.rowAtPoint(mousePos);  //Ascertain the mouse's row & column
                   mouseColumn = table.columnAtPoint(mousePos);
                   if(mouseRow == -1 || mouseColumn == -1)  //Ensure that the column is within the table
                        return;
                   columnClass = table.getColumnClass(mouseColumn); //Ascertain the column's class
                   if(columnClass != JButton.class) //If the class is not JButton, exit MouseForwarder
                        return;
                   button = (JButton)table.getValueAt(mouseRow, mouseColumn); //Access the button where the mouse clicked
                   e2 = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button); //Forward click to button
                   button.dispatchEvent(e2); //Have button take action
                   table.repaint(); //Repaint the table to ensure proper button animation
              //The 4 methods below are unused methods from the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         public static void main(String[] args) { //Setup and run the window
              JButtonJTableTest test = new JButtonJTableTest();
              test.setSize(300, 300);
              test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              test.setVisible(true);
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class JButtonRenderer implements TableCellRenderer {
         private TableCellRenderer defaultRenderer;
         private Component jTableButton;
         public JButtonRenderer(TableCellRenderer pRenderer) {
              defaultRenderer = pRenderer;
         public Component getTableCellRendererComponent(JTable pTable, Object pButton, boolean isSelected,
                                                                     boolean hasFocus, int pRow, int pCollumn) {
              try {
                   jTableButton = (Component)pButton;
                   return (Component)pButton;
              catch(ClassCastException exception) {
                   return defaultRenderer.getTableCellRendererComponent(pTable, pButton, isSelected,
                        hasFocus, pRow, pCollumn);
    }

    This question was crossposted into the Swing forum and should be answered there as that is the correct location for it http://forum.java.sun.com/thread.jspa?threadID=753812

  • How to put JTextfield and JButton in a cell of JTable

    I'm trying to put two Components into one cell of a JTable. This is no
    problem (in the TableCellRenderer) unless it comes to editing in these
    cells. I have written my own CellEditor for the table.but there is one
    minor problem: Neither the JTextfield nor the JButton has the focus so I
    can't make any input! Does anybody know what's wrong, please help me for this issue ,plese urgent

    Here you go
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    public class TableEdit extends JFrame
         JTable table = new JTable();
         private String[] columnNames = {"non-edit1", "edit", "non-edit2"};
         public TableEdit()
              super("Table Edit");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              createGUI();
              setLocationRelativeTo(null);
              setSize(400, 300);
              setVisible(true);
         private void createGUI()
              table.setModel(new DefaultTableModel(3,3)
                   public int getColumnCount()
                        return 3;
                   public boolean isCellEditable(int row, int column)
                        if(column == 1)
                             return true;
                        return false;
                   public String getColumnName(int column)
                        return columnNames[column];
                   public int getRowCount()
                        return 3;
                   public Class getColumnClass(int column)
                        return String.class;
                   public Object getValueAt(int row, int column)
                        return row + "" + column;
              table.setRowHeight(20);
              table.setDefaultEditor(String.class, new MyTableEditor());
              JScrollPane sp = new JScrollPane(table);
              add(sp);
         public class MyTableEditor extends AbstractCellEditor
         implements TableCellEditor
              JPanel jp = new JPanel(new BorderLayout(5,5));
              JTextField tf = new JTextField();
              JButton btn = new JButton("...");
              public MyTableEditor()
                   jp.add(tf);
                   jp.add(btn, BorderLayout.EAST);
                   btn.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e)
                             JOptionPane.showMessageDialog(null, "Clicked Lookup");
              public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
                   tf.setText(String.valueOf(value));
                   return jp;
              public Object getCellEditorValue()
                   return tf.getText();
         public static void main(String[] parms)
              new TableEdit();
    }

  • 3 jbuttons in a cell in a jtable

    hi i have a problem entering 3 buttons into 1 cell i a jtable
    can someone give me a good example how i put 3 buttons in the same cell
    i have a button render and its working good with 1 button but i just cant find a way to enter 3 buttons in the same cell
    tanks in advance

    Doesn't sound like a good design, but if you must, have the renderer return a JPanel with the 3 buttons, probably in a GridLayout or BoxLayout.
    I suppose you already know that the renderer only draws the components to the table cell, and your rendered buttons will not respond to mouse clicks or keyboard actions.
    db

  • Turn a single jtable cell into 2 swing component

    Hi, i'm trying to turn a jtable cell into two components, a jlabel and a jtextarea with the label on top of the textarea. Is that possible?
    I can write my own renderer and editor and turn a cell into a combobox or textarea. But is it possible to put two renderers in a single cell?
    thanks

    A JPanel IS-A Component so you could follow the procedure outlined in Sun's Tutorial and create a JPanel subclass that implements TableCellRenderer. For an editor the tutorial recommends subclassing AbstractCellEditor and implementing getTableCellEditorComponent() to return the panel containing your stuff.
    I haven't done this, but it seems worth a try. If you get stuck the best (most knowledgable, quickest) help is to be had from the [Swing forum|http://forum.java.sun.com/forum.jspa?forumID=57].
    Edited by: pbrockway2 on Jul 10, 2008 12:04 PM

Maybe you are looking for

  • Adobe Premiere Pro CS4 4.1.0 update  not working!files wrong size too?

    when i go to download Adobe Premiere Pro CS4 4.1.0 update it says that file size is 30.5MB but when it starts downloading it it says thats the file size is 110mb and once installed it wont let me import VOB files.  Has anyone got a solution? Thanks

  • Will there be an update in Pages for ipad that will allow for sub scripts and superscripts

    I am a chemistry professor who loves to work on the ipad. The problem I have is that the mathematics I use and chemical equations is use in my writings need both super scripts and subscripts. I would love to use my ipad for this, but presently, the o

  • Nokia Lumia 1520 having problems with Voyager Lege...

    I recently purchased Nokia Lumia 1520 and I am having some problems with Plantronics Voyager Legend. Before 1520 I was using HTC Radar 4G with Plantronics Voyager Legend and I don't have any problems. The problems that I am having are, when I am on a

  • 600 only works on external monitor

    I have tried 3 different screens, 2 different inverters, and still nothing.  But I have noticed that the little switch at the side, the head is missing and there are 3 prongs sticking up.  - Does anyone know what way these should be wired up?  If i c

  • Aus Microsoft NAV 2009 R2 Lieferscheine als PDF erstellen

    Hallo Wir würden gerne mit Adobe Acrobat PRo XI direkt aus NAV Lieferscheine erstellen. Weiss jemand wie man das "programmiertechnisch" anstellt? Auch wenn es nicht nur ein Lieferschein ist, sondern auch mehrere? Danke und Gruss