Adding JButton in a JTable

hi
i know this has been discussed quite a number of times before, but i still couldn't figure it out..
basically i just want to add a button to the 5th column of every row which has data in it.
this is how i create my table (partially)
     private JTable clientTable;
     private DefaultTableModel clientTableModel;
private JScrollPane scrollTable;
clientTableModel = new DefaultTableModel(columnNames,100);
          clientTable = new JTable(clientTableModel);
          TableColumn tblColumn1 = clientTable.getColumn("Request ID");
          tblColumn1.setPreferredWidth(70);
          tblColumn1 = clientTable.getColumn("Given Name");
          tblColumn1.setPreferredWidth(300);
          tblColumn1 = clientTable.getColumn("Address");
          tblColumn1.setPreferredWidth(350);
          tblColumn1 = clientTable.getColumn("Card Serial");
          tblColumn1.setPreferredWidth(100);
          tblColumn1 = clientTable.getColumn("Print Count");
          tblColumn1.setPreferredWidth(70);
          tblColumn1 = clientTable.getColumn("Print?");
          tblColumn1.setPreferredWidth(40);
          clientTableModel.insertRow(0,data);
          //clientTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
          scrollTable = new JScrollPane(clientTable);and i call this function void listInfoInTable(){
          JButton cmdPrint[];
          Vector columnNames = new Vector();
          Object[] data={"","","","","",""};
          Statement stmt=null;
          ResultSet rs=null;
          PreparedStatement ps;
          String query=null;
          String retrieve=null;
          int i,j=0;
          TableColumnModel modelCol = clientTable.getColumnModel();
          try{
               con = DriverManager.getConnection(url);
               JOptionPane.showMessageDialog(null,"Please wait while the program retrieves data.");
               query="select seqNo, givenName, address1, address2, address3, address4, cardSerNr, PIN1, PrintFlag from PendPINMail where seqNo<250;";
             ps = con.prepareStatement(query);
             rs=ps.executeQuery();
             while (rs.next()){
                  data[0]= rs.getString("seqNo");
                  data[1]= rs.getString("givenName");
                  data[2]= rs.getString("address1");
                  data[3]= rs.getString("cardSerNr");
                  data[4]= rs.getString("PrintFlag");
//                  modelCol.getColumn(5).setCellRenderer();
                  clientTableModel.insertRow(j,data);
                  j++;
          }catch (SQLException ex){
               JOptionPane.showMessageDialog(null,"Database error: " + ex.getMessage());
     } to display data from database inside the table.
How do I add JButton to the 5th column of each row? This documentation here http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#width says that i need to implement TableCellEditor to put JButton in the table. How do i really do it? I want the button to call another function which prints the data from the row (but this is another story).
Any help is greatly appreciated. Thanks

you would need CellRenderer i think that it is in
javax.swing.table.*;
see if you can get started with that.
Davidthanks, i'll try and have a look at it
Yes, that's definitely what you need to start with,
but you also need a CellEditor to return the
button as well, otherwise the button will not be
clickable (the renderer just paints the cell for
display, it doesn't allow you to interact with it).
You could maintain a list of components for rendering
each cell of the table so that your
CellRenderer and CellEditor always
return the same object (i.e. a JButton for any
given cell).
CB.thanks for the info.. could you point me to some examples? is sounds quite complicated for me....
thanks again

Similar Messages

  • 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;
    }

  • Changing the size of a jbutton inside a jtable

    Hi,
    I have found this example for adding a jbutton to a jtable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=715330
    however, I have cannot seem to figure out how to set the size of the jbutton. Currently, the jbutton is filled to the size of the cell within the jtable, but i want to have it a bit smaller and centered (the rows of my table are rather large in hieght)
    I tried the setSize()
    setPrefferedSize()
    setMinimumSize()
    setMaximumSize()methods, but nothing seems to work. Has anyone been able to do this?

    Use a JPanel instead of a JButton as cell renderer. Put a button inside the panel - use FlowLayout.

  • How to use JButton as a JTable column header?

    I'd like to use JButtons as my JTable's column headers.
    I built a JButton subclass which implemented TableCellRenderer and passed it to one of my table column's setHeaderRender method. The resulting header is a component that looks like a JButton but when clicked, it does not visually depress or fire any ActionEvents.

    You might want to check this example and use it accordingly for your requirements.
    http://www2.gol.com/users/tame/swing/examples/JTableExamples5.html
    Reason: The reason you're unable to perform actions on JButton is JTableHeader doesn't relay the mouse events to your JButtons.
    I hope this helps.
    have fun, ganesh.

  • How to include a jButton in the jTable CellEditor?

    sir,
    how can include a jButton in the jTable cell Editor as we include checkbox & Combo inthe Cell Editor?
    thks.

    There is c:import tag in the JSTL that will include the HTML from a file on another server.

  • JButtons into a JTable

    Is it possible for me to get a JButton into and JTable? The Table contents come from the code below.
    server myserver= new server();//make object of this class
    network mynetwork= new network(myserver);// make network objectand pass server as refrence
    int row,col;
              //initialise string database for hosts
              for (row=0;row<50;row++){               
                   myserver.hostdb[row][0]=""+iconButtons;
                   for (col=1;col<8;col++){
                   myserver.hostdb[row][col]="";
    Any help would be appriciated thanks.

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

  • Regarding adding Rows to a Jtable programmatically

    I tried adding rows to a Jtable programmatically.
    My Jtable has the Table Model as a class that has been extended from DefaultTAbleModel.
    I tried inserting rows using addRow, and setRowCount and set RowNum methods but nothing worked..
    and I get the OutOfMemory xecption alawys and my applet hangs...

    What's in your addRow method? Are you firing the
    inserted event with fireRowsInserted?
    My snippet assumes you're storing table data in a
    vector of vectors and only want to add the row to the
    bottom of the table.
    public void addRow(Vector vector)
    data.add(vector);
    fireTableRowsInserted(data.size(),
    size(), data.size());
    addRow is a method of the DefaultTableModel class..and so I am not over riding it...
    i just use it as defaulttablemodel-object.addRow(Object[] obj);

  • Adding JButton, JTextField to scroll pane...

    I have developed an appln in which I have added JPanel to JFrame.
    To this JPanel I m adding JButton & JTextField. But the JButton & JTextField are increasing dynamically in my appln[according to DBMS query]. So I wanted to use scrolpane or something like so that the window can be scrolled vertically to view all the components[JButton & JTextField]. I m developing this as a standalone appln.
    Plz help..
    Thanking in advance.

    Thanx fouadk ,
    But my problem still persists. Now though I m able to add JPanel to JScrollPane, but when the components in the JPanel increase than the height of the Pane, the components at the dowm are not visible unless I resize the window by manually dragging the corners. Actually I wanted to keep the size of the window constant and make use of the VERTICAL SCROLLBAR.
    Plz help.
    Thanking in advance.
    Following is code:
    import javax.swing.*;
    public class testt extends JFrame {
    private JPanel p = new JPanel();
    private JScrollPane sp = new JScrollPane(p
    ,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
    ,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    private JButton b[] = new JButton[15];
    public testt() {
    super("TEST");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(500, 400);
    setLocation(50, 20);
    this.add(sp);
    p.setLayout(null);
    sp.setAutoscrolls(true);
    for(int i = 0, y = 10; i < 15; i++, y += 40)
         b[i] = new JButton("BUTTON "+ (i+1));
         b.setBounds(10,y,100,20);
         p.add(b[i]);
    public static void main(String[] args) {
    testt t = new testt();
    t.setVisible(true);

  • 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 .....

  • Problem in adding/deleting rows in JTable

    I am trying to add /remove rows from JTable whose first column is JButton and others are JComboBox's.If no rows are selected,new row is added at the end.If user selects some row & then presses insert button,new row is added below it.Rows can only be deleted if user has made some selection.Kindly help me,where i am making mistake.If any function is to be used.My code is as follows....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class JButtonTableExample extends JFrame implements ActionListener{
    JComboBox mComboLHSType = new JComboBox();
    JComboBox mComboRHSType = new JComboBox();
    JLabel mLabelLHSType = new JLabel("LHS Type");
    JLabel mLabelRHSType = new JLabel("RHS Type");
    JButton mButtonDelete = new JButton("Delete");
    JButton mButtonInsert = new JButton("Insert");
    JPanel mPanelButton = new JPanel();
    JPanel mPanelScroll = new JPanel();
    JPanel mPanelCombo = new JPanel();
    DefaultTableModel dm ;
    JTable table;
    int currentRow = -1;
    static int mSelectedRow = -1;
    public JButtonTableExample()
    super( "JButtonTable Example" );
    makeForm();
    setSize( 410, 222 );
    setVisible(true);
    private void makeForm()
    this.getContentPane().setLayout(null);
    mPanelCombo.setLayout(null);
    mPanelCombo.setBorder(new LineBorder(Color.red));
    mPanelCombo.setBounds(new Rectangle(1,1,400,30));
    mLabelLHSType.setBounds(new Rectangle(26,5,71,22));
    mComboLHSType.setBounds(new Rectangle(83,5,100,22));
    mLabelRHSType.setBounds(new Rectangle(232,5,71,22));
    mComboRHSType.setBounds(new Rectangle(292,5,100,22));
    mPanelCombo.add(mLabelLHSType,null);
    mPanelCombo.add(mComboLHSType,null);
    mPanelCombo.add(mLabelRHSType,null);
    mPanelCombo.add(mComboRHSType,null);
    mPanelScroll.setLayout(null);
    mPanelScroll.setBorder(new LineBorder(Color.blue));
    mPanelScroll.setBounds(new Rectangle(1,28,400,135));
    mPanelButton.setLayout(null);
    mPanelButton.setBorder(new LineBorder(Color.green));
    mPanelButton.setBounds(new Rectangle(1,165,400,30));
    mButtonInsert.setBounds(new Rectangle(120,5,71,22));
    mButtonDelete.setBounds(new Rectangle(202,5,71,22));
    mButtonDelete.addActionListener(this);
    mButtonInsert.addActionListener(this);
    mPanelButton.add(mButtonDelete,null);
    mPanelButton.add(mButtonInsert,null);
    dm = new DefaultTableModel();
    //dm.setDataVector(null,
    //new Object[]{"Button","Join","LHS","Operator","RHS"});
    dm.setDataVector(new Object[][]{{"","","","",""}},
    new Object[]{"","Join","LHS","Operator","RHS"});
    table = new JTable(dm);
    table.getTableHeader().setReorderingAllowed(false);
    table.setRowHeight(25);
    int columnWidth[] = {20,45,95,95,95};
    TableColumnModel modelCol = table.getColumnModel();
    for (int i=0;i<5;i++)
    modelCol.getColumn(i).setPreferredWidth(columnWidth);
    //modelCol.getColumn(0).setCellRenderer(new ButtonRenderer());
    //modelCol.getColumn(0).setCellEditor(new ButtonEditor(new JCheckBox()));
    modelCol.getColumn(0).setCellRenderer(new ButtonCR());
    modelCol.getColumn(0).setCellEditor(new ButtonCE(new JCheckBox()));
    modelCol.getColumn(0).setResizable(false);
    setUpJoinColumn(modelCol.getColumn(1));
    setUpLHSColumn(modelCol.getColumn(2));
    setUpOperColumn(modelCol.getColumn(3));
    setUpRHSColumn(modelCol.getColumn(4));
    JScrollPane scroll = new JScrollPane(table);
    scroll.setBounds(new Rectangle(1,1,400,133));
    mPanelScroll.add(scroll,null);
    this.getContentPane().add(mPanelCombo,null);
    this.getContentPane().add(mPanelScroll,null);
    this.getContentPane().add(mPanelButton,null);
    }//end of makeForm()
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource() == mButtonInsert)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before Insert CURRENT ROW"+currentRow);
    if(currentRow == -1)
    int rowCount = dm.getRowCount();
    //mSelectedRow = rowCount-1;
    //table.clearSelection();
    dm.insertRow(rowCount,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    else
    table.clearSelection();
    dm.insertRow(currentRow+1,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("After INSERT CURRENT ROW"+currentRow);
    if(ae.getSource() == mButtonDelete)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before DELETE CURRENT ROW"+currentRow);
    if(currentRow != -1)
    dm.removeRow(currentRow);
    table.clearSelection();
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("Selected Row"+mSelectedRow);
    else
    JOptionPane.showMessageDialog(null, "Select row first", "alert", JOptionPane.ERROR_MESSAGE);
    //System.out.println("DELETE CURRENT ROW"+currentRow);
    public void setUpJoinColumn(TableColumn joinColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("AND");
    comboBox.addItem("OR");
    comboBox.addItem("NOT");
    joinColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    joinColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = joinColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpLHSColumn(TableColumn LHSColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Participant1");
    comboBox.addItem("Participant2");
    comboBox.addItem("Variable1");
    LHSColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    LHSColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = LHSColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpOperColumn(TableColumn operColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("=");
    comboBox.addItem("!=");
    comboBox.addItem("Contains");
    operColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    operColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = operColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpRHSColumn(TableColumn rhsColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Variable1");
    comboBox.addItem("Constant1");
    comboBox.addItem("Constant2");
    rhsColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    rhsColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = rhsColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public static void main(String[] args) {
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Button as a renderer for the table cells
    class ButtonCR implements TableCellRenderer
    JButton btnSelect;
    public ButtonCR()
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    if (column != 0) return null; //meany !!!
    //System.out.println("Inside renderer########################Selected row");
    //btnSelect.setText(value.toString());
    //btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    return btnSelect;
    }//end fo ButtonCR
    //Default Editor for table
    class ButtonCE extends DefaultCellEditor implements ActionListener
    JButton btnSelect;
    JTable table;
    //Object val;
    static int selectedRow = -1;
    public ButtonCE(JCheckBox whoCares)
    super(whoCares);
    //this.row = row;
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    btnSelect.addActionListener(this);
    setClickCountToStart(1);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column)
    if (column != 0) return null; //meany !!!
    this.selectedRow = row;
    this.table = table;
    table.clearSelection();
    System.out.println("Inside getTableCellEditorComponent");
    return btnSelect;
    //public Object getCellEditorValue()
    //return val;
    public void actionPerformed(ActionEvent e)
    // Your Code Here...
    System.out.println("Inside actionPerformed");
    System.out.println("Action performed Row selected "+selectedRow);
    btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    }//end of ButtonCE

    Hi,
    All the thing you have to do is to return a boolean for the column. JTable will use a checkbox (as default) to show boolean values.

  • Adding data dynamically to JTable with a filter - getting error

    Hello,
    I am using JTable, and adding data and displaying it worked fine
    until I tried adding a filter,
    can anyone tell me what am I doing wrong or
    why am I getting this Error?
    The Error message
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:501)
            at javax.swing.JTable.convertRowIndexToModel(JTable.java:2620)
            at javax.swing.JTable.getValueAt(JTable.java:2695)
            at javax.swing.JTable.prepareRenderer(JTable.java:5712)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2075)
            at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1977)
            at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1773)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143)
            at javax.swing.JComponent.paintComponent(JComponent.java:763)
            at javax.swing.JComponent.paint(JComponent.java:1027)
            at javax.swing.JComponent.paintChildren(JComponent.java:864)
            at javax.swing.JComponent.paint(JComponent.java:1036)
            at javax.swing.JViewport.paint(JViewport.java:747)
            at javax.swing.JComponent.paintChildren(JComponent.java:864)
            at javax.swing.JComponent.paint(JComponent.java:1036)
            at javax.swing.JComponent.paintToOffscreen(JComponent.java:5122)
            at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:277)
            at javax.swing.RepaintManager.paint(RepaintManager.java:1217)
            at javax.swing.JComponent._paintImmediately(JComponent.java:5070)
            at javax.swing.JComponent.paintImmediately(JComponent.java:4880)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:803)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
            at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
            at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)I am also using my own class that extends "AbstractTableModel"
    as TableModel,
    public class MyTableModel extends AbstractTableModel  {
        ArrayList<TableData> tableData=new ArrayList<TableData>(10);
        String[] columnNames=new String[]{"S/N"," Time (mili)","SD","SA","SSAP","DA","DSAP","FC","DATA"};   
        public void addRow(TableData data){
            tableData.add(data);
            fireTableDataChanged();
        @Override
        public int getRowCount() {
            return tableData.size();
        public TableData getRow(int i){
            return tableData.get(i);
        @Override
        public int getColumnCount() {
            return columnNames.length;
        @Override
        public String getColumnName(int col) {
                return columnNames[col];
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return tableData.get(rowIndex).getValue(columnIndex);
        }The Row Filter class
    class myRowFilter extends RowFilter<MyTableModel,Integer>{
            @Override
            public boolean include(Entry<? extends MyTableModel, ? extends Integer> entry) {
                // Entry < SomeCostumTableModel , Integer> entry   ; Integer =Identifier= Row Number
                boolean frame_type;
                MyTableModel model=entry.getModel();
                TableData data=model.getRow(entry.getIdentifier());
                frame_type=((SD1&&data.SD==TableData.SD1) ||
                                             (SD2&&data.SD==TableData.SD2) ||
                                             (SD3&&data.SD==TableData.SD3) ||
                                             (SD4&&data.SD==TableData.SD4) ||
                                             (SC&&data.SD==TableData.SC) );
               return frame_type;
        }and How I add the filter to the Table
        private MyTableModel myTableModel=new MyTableModel();
        private RowSelectionListener rowSelectionListener=new RowSelectionListener();
        TableRowSorter<MyTableModel> sorter=new TableRowSorter<MyTableModel>(myTableModel);
        private FilterFrame filterFrame=new FilterFrame(this);
        // then in the constructor of the main frame
        // I call this
            sorter.setRowFilter(filterFrame.filter);
            MainTable.setRowSorter(sorter);
            sorter.setSortsOnUpdates(true);Edited by: YellowMurdoch on Nov 17, 2009 6:31 AM
    Edited by: YellowMurdoch on Nov 17, 2009 6:31 AM

    Thanks for noting that.
    you mean like this?
    public void addEntry(TableData data){
            myTableModel.addRow(data);
            javax.swing.SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                        myTableModel.fireTableRowsInserted(0,0);
        }both work,
    would putting "invokeLater" inside "addEntry" somehow mess other things?
    i guess that means addRow() is not supposed to update the table graphically?
    Edited by: YellowMurdoch on Nov 17, 2009 9:30 AM
    Edited by: YellowMurdoch on Nov 17, 2009 9:33 AM

  • Problems adding info to a JTable

    Hi, list,
    I was figthing all this week with a JTable issue and I haven't more resources to try. I think that it's a complex problem to explain, but I'll try it as well I can.
    SCENARIO:
    - There is a panel with 2 JTables (sqlServerJTable and oracleJTable) and a button (loadSQLServerCampaignAction).
    - Each table has different instances of CampaignTableModel [6 columns].
    - Initially,
    sqlServerJTable.getModel() --> 0 rows
    oracleJTable.getModel() --> 3 rows
    - The button's action show a new panel to register a new instance of CampagnaTableInfo. When push accept in this panel, I catch the CampaignTableInfo object and add it to sqlServerJTable.getModel().
    Simple?
    The problems starts now...
    Randomly, we obtain these issues:
    1) Data added without execeptions [Desired result]
    2) No effect: No data added to sqlServerJTable and no Exceptions
    3) Data added with exceptions
    4) No data added with exceptions
    EXCEPTIONS: With the same CampaignTableInfo object, obtain different index on the exception each time.
    =================================================================================
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 3 >= 2
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
            at javax.swing.plaf.basic.BasicTableHeaderUI.paint(BasicTableHeaderUI.java:609)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143)
            at javax.swing.JComponent.paintComponent(JComponent.java:763)
            at javax.swing.JComponent.paint(JComponent.java:1027)
            at javax.swing.JComponent.paintToOffscreen(JComponent.java:5122)
            at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:285)
            at javax.swing.RepaintManager.paint(RepaintManager.java:1128)
            at javax.swing.JComponent._paintImmediately(JComponent.java:5070)
            at javax.swing.JComponent.paintImmediately(JComponent.java:4880)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:723)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:679)
            at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:659)
            at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
            at java.awt.Dialog$1.run(Dialog.java:1045)
            at java.awt.Dialog$3.run(Dialog.java:1097)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1095)
            at java.awt.Component.show(Component.java:1422)
            at java.awt.Component.setVisible(Component.java:1375)
            at java.awt.Window.setVisible(Window.java:806)
            at java.awt.Dialog.setVisible(Dialog.java:985)
            at es.dap.pac.apps.cargaecsi.view.CargaECSIView.viewDialog(CargaECSIView.java:108)
            at es.dap.pac.apps.cargaecsi.controller.MaestrasCampagnaController.manageCampagnas(MaestrasCampagnaController.java:47)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:662)
            at org.jdesktop.application.ApplicationAction.actionPerformed(ApplicationAction.java:698)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at org.jdesktop.swingx.JXHyperlink.fireActionPerformed(JXHyperlink.java:244)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
            at java.awt.Component.processEvent(Component.java:5806)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4413)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2440)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)=================================================================================
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
            [...]=================================================================================
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
    [continue...]

    I'll try to show only the relevant code:
    =================================================================================
    CampaignTableInfo (A bean with 6 attributes, setters and getters)
    =================================================================================
    CampaignTableModel
    public class CampagnasTableModel extends MyAbstractTableModel<CampagnaTableInfo> {
        private String columnNames[] = {"Campaña", "Descripción", "Fecha Inicio Campaña",
            "Fecha Inicio Control", "Fecha Final Campaña", "Fecha Disponibilidad"};
        public CampagnasTableModel(List<CampagnaTableInfo> data) {
            this.data = data;
        public int getColumnCount() {
            return columnNames.length;
        @Override
        public String getColumnName(int c) {
            return columnNames[c];
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object result = null;
            if (rowIndex >= this.data.size()) {
                System.err.println("-->");
            } else {
                switch (columnIndex) {
                    case 0:
                        result = this.data.get(rowIndex).getIdCampaña();
                        break;
                    case 1:
                        result = this.data.get(rowIndex).getDsCampaña();
                        break;
                    case 2:
                        if (this.data.get(rowIndex).getFhInicioCampaña() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhInicioCampaña());
                        break;
                    case 3:
                        if (this.data.get(rowIndex).getFhInicioControl() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhInicioControl());
                        break;
                    case 4:
                        if (this.data.get(rowIndex).getFhFinalCampaña() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhFinalCampaña());
                        break;
                    case 5:
                        if (this.data.get(rowIndex).getFhDisponibilidad() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhDisponibilidad());
                        break;
            return result;
        @Override
        public Class getColumnClass(int c) {
            return String.class;
    }=================================================================================
    MyAbstractTableModel
    public abstract class MyAbstractTableModel<TIPO> extends AbstractTableModel{
        protected List<TIPO> data;
        public List<TIPO> getDataModel() {
            return this.data;
        public int getRowCount() {
            int result = 0;
            if(data != null) {
                result = data.size();
            return result;
        public void addData(TIPO tipo) {
            this.data.add(tipo);
            this.fireTableDataChanged();
    }=================================================================================
    CampagnasPanel
    public class CampagnasPanel extends JPanel {
        private CampagnasService service;
        /** Creates new form CampagnasPanel */
        public CampagnasPanel() {
            this.service = new CampagnasService(this);
            initComponents();
            postInitComponents();
        public void setSQLServerTableModel(List<CampagnaTableInfo> tableModel) {
            CampagnasTableModel campagnasTableModel = new CampagnasTableModel(tableModel);
            this.sqlServerTable.setModel(campagnasTableModel);
            this.sqlServerTable.packAll();
        public void setOracleTableModel(List<CampagnaTableInfo> tableModel) {
            CampagnasTableModel campagnasTableModel = new CampagnasTableModel(tableModel);
            this.oracleTable.setModel(campagnasTableModel);
            this.oracleTable.packAll();
        private void postInitComponents() {
            this.createButton.setAction(CargaECSIController.getInstance().getMaestrasCampañaController().getAction("createCampagna"));
        public CampagnasTableModel getCampagnasTableModel() {
            return (CampagnasTableModel) sqlServerTable.getModel();
    }[continue...]

  • Multiple JButtons in a JTable cell: handling events

    Hello!
    I'm trying to develop a Swing application which makes use of tables in several panels.
    Each row of each table should present the user two buttons, one for editing the row, one for viewing details of that row. Both editing and viewing are done in another panel.
    I thought I could add the buttons as the last column of each row, so I made a panel which holds the two buttons and the id of the row, so that I know what I have to edit or view.
    I managed to insert the panel as the last column, but I can't have the buttons click.
    I studied cell renderers and editors from several tutorials and examples, but evidently I can't understand either of them: whatever I try doesn't change the outcome... :(
    Below is the code I use, except for imports and packages:
    ActionPanel.java - The panel which holds the buttons and the row id
    public class ActionPanel extends JPanel{
      private static final long serialVersionUID = 1L;
      public static String ACTION_VIEW="view";
      public static String ACTION_EDIT="edit";
      private String id;
      private JButton editButton;
      private JButton viewButton;
      public String getId() {
        return id;
      public void setId(String id) {
        this.id = id;
      public JButton getEditButton() {
        return editButton;
      public void setEditButton(JButton editButton) {
        this.editButton = editButton;
      public JButton getViewButton() {
        return viewButton;
      public void setViewButton(JButton viewButton) {
        this.viewButton = viewButton;
      public ActionPanel() {
        super();
        init();
      public ActionPanel(String id) {
        super();
        this.id = id;
        init();
      private void init(){
        setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0))
        editButton=new JButton(new ImageIcon("./images/icons/editButtonIcon.png"));
        editButton.setBorderPainted(false);
        editButton.setOpaque(false);
        editButton.setAlignmentX(TOP_ALIGNMENT);
        editButton.setMargin(new Insets(0,0,0,0));
        editButton.setSize(new Dimension(16,16));
        editButton.setMaximumSize(new Dimension(16, 16));
        editButton.setActionCommand(ACTION_EDIT);
        editButton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, id, "Editing", JOptionPane.INFORMATION_MESSAGE);
        viewButton=new JButton(new ImageIcon("./images/icons/viewButtonIcon.png"));
        viewButton.setMaximumSize(new Dimension(16, 16));
        viewButton.setActionCommand(ACTION_VIEW);
        viewButton.setBorderPainted(false);
        viewButton.setOpaque(false);
        viewButton.setMargin(new Insets(0,0,0,0));
        viewButton.setSize(new Dimension(16,16));
        viewButton.setMaximumSize(new Dimension(16, 16));
        viewButton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, id, "Viewing", JOptionPane.INFORMATION_MESSAGE);
        add(viewButton);
        add(editButton);
    ActionPanelRenerer.java - the renderer for the above panel
    public class ActionPanelRenderer implements TableCellRenderer{
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component ret=(Component)value;
        if (isSelected) {
          ret.setForeground(table.getSelectionForeground());
          ret.setBackground(table.getSelectionBackground());
        } else {
          ret.setForeground(table.getForeground());
          ret.setBackground(UIManager.getColor("Button.background"));
        return ret;
    ActionPanelEditor.java - this is the editor, I can't figure out how to implement it!!!!
    public class ActionPanelEditor extends AbstractCellEditor implements TableCellEditor{
      public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
        return (ActionPanel)value;
      public Object getCellEditorValue() {
        return null;
    ServicesModel.java - The way I fill the table is through a model:
    public class ServicesModel extends AbstractTableModel  {
      private Object[][] data;
      private String[] headers;
      public ServicesModel(Object[][] services, String[] headers) {
        this.data=services;
        this.headers=headers;
      public int getColumnCount() {
        return headers.length;
      public int getRowCount() {
        return data.length;
      public Object getValueAt(int row, int col) {
        if(col==data.length-1)
          return new ActionPanel(""+col);
        else
          return data[row][col];
      public boolean isCellEditable(int row, int col) {
        return false;
      public Class getColumnClass(int column) {
        return getValueAt(0, column).getClass();
    ServicesList.java - The panel which holds the table (BasePanel is a custom class, not related to the table)
    public class ServicesList extends BasePanel {
      private JLabel label;
      private JTable grid;
      public ServicesList(SessionManager sessionManager){
        super(sessionManager);
        grid=new JTable() ;
        add(new JScrollPane(grid), BorderLayout.CENTER);
        layoutComponents();
      public void layoutComponents(){
        ConfigAccessor dao=new ConfigAccessor(connectionUrl, connectionUser, connectionPass);
        String[] headers=I18N.get(dao.getServiceLabels());
        grid.setModel(new ServicesModel(dao.getServices(), headers));
        grid.setRowHeight(20);
        grid.getColumnModel().getColumn(headers.length-1).setCellRenderer(new ActionPanelRenderer());
        grid.setDefaultEditor(ActionPanel.class, new ActionPanelEditor());
        grid.removeColumn(grid.getColumnModel().getColumn(0));
        dao.close();
    }Please can anyone at least address me to what I'm doing wrong? Code would be better, but examples or hints will do... ;)
    Thank you very much in advance!!!

    Hello!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class MultipleButtonsInCellTest {
      public JComponent makeUI() {
        String[] columnNames = {"String", "Button"};
        Object[][] data = {{"AAA", null}, {"BBB", null}};
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {
          @Override public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        JTable table = new JTable(model);
        table.setRowHeight(36);
        ActionPanelEditorRenderer er = new ActionPanelEditorRenderer();
        TableColumn column = table.getColumnModel().getColumn(1);
        column.setCellRenderer(er);
        column.setCellEditor(er);
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(table));
        p.setPreferredSize(new Dimension(320, 200));
        return p;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new MultipleButtonsInCellTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    class ActionPanelEditorRenderer extends AbstractCellEditor
                       implements TableCellRenderer, TableCellEditor {
      JPanel panel1 = new JPanel();
      JPanel panel2 = new JPanel();
      public ActionPanelEditorRenderer() {
        super();
        JButton viewButton2 = new JButton(new AbstractAction("view2") {;
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Viewing");
        JButton editButton2 = new JButton(new AbstractAction("edit2") {;
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Editing");
        panel1.setOpaque(true);
        panel1.add(new JButton("view1"));
        panel1.add(new JButton("edit1"));
        panel2.setOpaque(true);
        panel2.add(viewButton2);
        panel2.add(editButton2);
      @Override
      public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
        panel1.setBackground(isSelected?table.getSelectionBackground()
                                       :table.getBackground());
        return panel1;
      @Override
      public Component getTableCellEditorComponent(JTable table, Object value,
                                    boolean isSelected, int row, int column) {
        panel2.setBackground(table.getSelectionBackground());
        return panel2;
      @Override
      public Object getCellEditorValue() {
        return null;
    }

  • Renderer problem for a JButton in a JTable

    Hi all,
    Here is my requirement -
    When the value of a particular cell in a JTable gets changed, another cell in the same selected row should display a JButton. The button should remain displayed for that row. Other rows should not have the button displayed unless there is any change in value of other columns in that row.
    I have the problem in displaying the button only when the values of a particular row is changed. The button gets displayed if I click that button cell which should not happen as the values are not changed for the corresponding row. Also, once the button is displayed for a particular row, if i click some other row, button gets disappeared for the previously selected row.
    Here is the code I have implemented. Please correct me where I am going wrong.
    Renderer code for the button-
    ==================
    class ButtonRenderer extends JButton implements TableCellRenderer {
    public ButtonRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    } else{
    setForeground(table.getForeground());
    setBackground(UIManager.getColor("Button.background"));
    TableModel model = table.getModel();
    // get values from the table model's selected row and specific column
    if(// check if values are changed from old ones)
    setText("Undo");
    setVisible(true);
    return (JButton) value;
    else
    JButton button = new JButton("");
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0, 0, 0, 0));
    button.setEnabled(false);
    return button;
    Editor code for the button -
    =======================
    class ButtonCellEditor extends DefaultCellEditor
    public ButtonCellEditor(JButton aButton)
    super(new JTextField());
    setClickCountToStart(0);
    aButton.setOpaque(true);
    aButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    editorComponent = aButton;
    protected void fireEditingStopped()
    super.fireEditingStopped();
    public Object getCellEditorValue()
    return editorComponent;
    public boolean stopCellEditing()
    return super.stopCellEditing();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    return editorComponent;
    Code setting the renderer/editor -
    ==================================
    TableColumn column = colModel.getColumn(6);
    button.setVisible(true);
    button.setEnabled(true);
    column .setCellRenderer(new ButtonRenderer());
    column .setCellEditor(new ButtonCellEditor(button));
    Please correct me where I am going wrong.
    Thanks in advance!!

    Hope this is what you want...edit the column "Value" and type "Show" to get the desired result.
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    public class TableEdit2 extends JFrame
         Object[] columns =
         { "A", "Value", "Action" };
         Object[][] data =
         { "A0", "B0", "" },
         { "A1", "B1", "" },
         { "A2", "B2", "" },
         { "A3", "B3", "" },
         { "A4", "B4", "" },
         { "A5", "B5", "" },
         { "A6", "B6", "" },
         { "A7", "B7", "" },
         { "A8", "B8", "" },
         { "A9", "B9", "" },
         { "A10", "B10", "" },
         { "A11", "B11", "" } };
         JTable table = null;
         public TableEdit2()
              super("Table Edit");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              createGUI();
              setLocationRelativeTo(null);
              setSize(400, 300);
              setVisible(true);
         private void createGUI()
              table = new JTable(data, columns)
                   public void setValueAt(Object value, int row, int column)
                        super.setValueAt(value, row, column);
                        ((AbstractTableModel) table.getModel()).fireTableRowsUpdated(
                                  row, row);
              table.getColumn("Action").setCellRenderer(new ButtonRenderer());
              table.getColumn("Action").setCellEditor(new MyTableEditor(new JTextField()));
              JScrollPane sc = new JScrollPane(table);
              add(sc);
         class ButtonRenderer extends DefaultTableCellRenderer
              JButton undoButton = new JButton("Undo");
              public ButtonRenderer()
                   super();
              public Component getTableCellRendererComponent(JTable table,
                        Object value, boolean isSelected, boolean hasFocus, int row,
                        int column)
                   Component comp = super.getTableCellRendererComponent(table, value,
                             isSelected, hasFocus, row, column);
                   if (column == 2)// The Action Column
                        Object checkValue = table.getValueAt(row, 1);
                        if ("Show".equals(String.valueOf(checkValue)))
                             return undoButton;
                   return comp;
         class MyTableEditor extends DefaultCellEditor
              JButton undoButton = new JButton("Undo");
              public MyTableEditor(JTextField dummy)
                   super(dummy);
                   setClickCountToStart(0);
                   undoButton.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             JOptionPane.showMessageDialog(null, "Do your Action Here");
              public Component getTableCellEditorComponent(JTable table,
                        Object value, boolean isSelected, int row, int column)
                   Component comp = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   if (column == 2)// The Action Column
                        Object checkValue = table.getValueAt(row, 1);
                        if ("Show".equals(String.valueOf(checkValue)))
                             return undoButton;
                   return comp;
              public Object getCellEditorValue()
                   return "";
          * @param args
         public static void main(String[] args)
              // TODO Auto-generated method stub
              new TableEdit2();
    }

  • Using JButtons in a JTable

    I'm trying to find some information about how to use a JButton within a cell of a JTable. I'm able to insert the button using a custom cell renderer. Basically I create my own renderer which is triggered for JButton.class. That works well.
    Of course I do a addActionListener() on the JButton so something will happen when it is pressed.
    But the problem is that events aren't getting through to the button at all. The table is getting all the mouse events and is not passing them on.
    I'm sure I'm not the first to run into this. Any suggestions on how to get the events to the button, or otherwise deal with this problem?
    Thanks

    Those example are from 1998. I don't think they work anymore.
    Basically, if I could just find a way to get the JTable to send any kind of event to any class that I can write, I would be happy. That would do the trick.
    One possibility is to just use a mouse listener, although that seems like a very low-level way to do something which should be at a higher level. But that seems like the only way. Try as I might, I can't find a way to set an editor for these cells.
    I used table.setDefaultEditor(JButton.class, myTableCellEditor), and I tried to set it on the column, too, but myTableCellEditor never gets called in response to events.
    Any other approaches?
    Thanks

Maybe you are looking for

  • Exporting PDFs in InDesign CC fails

    I have tried to export a multi page Indesign document to PDF but it keeps failing. The document was created in CS 5.5 and exported without any problems in this version. I've recently upgraded to CC and have experienced a few problems when exporting t

  • Not Able to Update the PSA Request.

    Hi All, I am facing one Problem I am having 10 requests in my PSA.9 requests are updated in to my Data Target but last 10th request is having some erroneous records which I didnu2019t notice that error records next day I have seen the error request i

  • Missing history in ABAP Development forum

    When I look at the main page of the ABAP Development forum, I only see two pages of history. When I look at a sub-forum, I see lots of pages. Is it just me? (I have set my display to 50 items per page.) Just noticed - same behavior here in Community

  • Multi-lingual String Shortening

    Hey all, I've got a program that allows the user to name certain objects. These names need to be displayed in a variety of places and there may different amounts of space. I didn't like JLabel's default way of displaying names that are too long to fi

  • Reader x download problem with Adobe 8?

    Trying to download Adobe reader X (10.1.4) but the download stops because it thinks filies it needs are being used by Adobe Reader 8.3. 8.3 stopped working.  I tried to uninstall 8.3 but no luck.  Tried rebooting the system - no luck.  Any suggestion