Search code examples
javajtabletablecelleditor

JTable , Celleditor , how do i startCellEditing?


I have JTable and couple of Cells as rows ( only 1 column ) that have Textboxes On Double Clicking a particular Cell , user can edit the cell But i have a separate Edit button part of application for editing the cells since there is no "startCellEditing" method on getting getCellEditor (only stopCellEditing is there )

if i call editCellAt(row,column) method (on clicking the edit button ) its removing the existing content and user has to enter the entire content again .

how do i get this behavior ? Inshort , instead of user double clicking the cell to edit , he clicks on a edit button , how do achieve same behavior ?


Solution

  • this code do not clears cell content on button click

    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class Test extends JFrame {
    
        public Test() {
    
            DefaultTableModel tableModel = new DefaultTableModel();
            tableModel.setRowCount(2);
            tableModel.setColumnCount(2);
            tableModel.setValueAt("Foo", 0, 0);
            final JTable t = new JTable(tableModel);
    
            JPanel comp = new JPanel(new BorderLayout());
            getContentPane().add(comp);
    
            comp.add(t, BorderLayout.CENTER);
            JButton edit = new JButton("Edit");
            edit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    t.editCellAt(0, 0);
                }
            });
            comp.add(edit, BorderLayout.SOUTH);
    
            pack();
            setVisible(true);
    
        }
    
        public static void main(String[] args) {
            new Test();
        }
    }