Search code examples
javaswingnetbeansjtabletablemodel

How to set celleditor false in JTable in netbeans IDE in java?


  1. Here is my code which has no error
  2. In this code it is possible to edit each cell

How to prevent the cell being edited?

I am using DefaultTable model

    package TableModels;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.table.DefaultTableModel;

    /**
     *
     * @author  DELL
     */
    public class TableModels extends javax.swing.JFrame {

        /** Creates new form TableModels */
        DefaultTableModel dtm;

        String name;
        String age;
        String gender;



        public TableModels() 
        {
        initTables();      

        initComponents();

        initListener();
        }

        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        lbl_name = new javax.swing.JLabel();
        lbl_age = new javax.swing.JLabel();
        lbl_gender = new javax.swing.JLabel();
        txt_name = new javax.swing.JTextField();
        txt_age = new javax.swing.JTextField();
        txt_gender = new javax.swing.JTextField();
        btn_add = new javax.swing.JButton();
        btn_remove = new javax.swing.JButton();
        btn_update = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        table.setModel(dtm);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
            tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        lbl_name.setText("Name");

        lbl_age.setText("Age");

        lbl_gender.setText("Gender");

        btn_add.setText("Add");

        btn_remove.setText("Remove");

        btn_update.setText("Update");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_name)
                    .addComponent(lbl_age)
                    .addComponent(lbl_gender))
                .addGap(58, 58, 58)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txt_name, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
                    .addComponent(txt_age)
                    .addComponent(txt_gender)
                    .addGroup(layout.createSequentialGroup()
                    .addComponent(btn_add)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btn_update)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btn_remove))))
                .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(25, 25, 25)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lbl_name)
                .addComponent(txt_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lbl_age)
                .addComponent(txt_age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lbl_gender)
                .addComponent(txt_gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btn_add)
                .addComponent(btn_remove)
                .addComponent(btn_update))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
        );

        pack();
        }// </editor-fold>

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
        txt_name.setText(dtm.getValueAt(table.getSelectedRow(), 0).toString());
        txt_age.setText(dtm.getValueAt(table.getSelectedRow(), 1).toString());
        txt_gender.setText(dtm.getValueAt(table.getSelectedRow(), 2).toString());
    }

        /**
        * @param args the command line arguments
        */

        public void initTables()
        {
        dtm=new DefaultTableModel(0,0);

        dtm.addColumn("Name");
        dtm.addColumn("Age");
        dtm.addColumn("Gender"); 

        }



        public void initListener()
        {
        ActionListener al=new ActionListener()
        {
            public void actionPerformed(ActionEvent ae) 
            {
               if(ae.getSource()==btn_add)
               {
               name=txt_name.getText();
               age=txt_age.getText();
               gender=txt_gender.getText();

               Object data[]=new Object[3];

               data[0]=name;
               data[1]=age;
               data[2]=gender;

               dtm.addRow(data);


               }

               if(ae.getSource()==btn_update)
               {
               name=txt_name.getText();
               age=txt_age.getText();
               gender=txt_gender.getText();

               Object data[]=new Object[3];

               data[0]=name;
               data[1]=age;
               data[2]=gender;

               dtm.setValueAt(data[0], table.getSelectedRow(), 0);
               dtm.setValueAt(data[1], table.getSelectedRow(), 1);
               dtm.setValueAt(data[2], table.getSelectedRow(), 2);
               }
               if(ae.getSource()==btn_remove)
               {
               dtm.removeRow(table.getSelectedRow());
               }
            }
        };
        btn_add.addActionListener(al);
        btn_update.addActionListener(al);
        btn_remove.addActionListener(al);
        }


        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            new TableModels().setVisible(true);
            }
        });
        }

        // Variables declaration - do not modify
        private javax.swing.JButton btn_add;
        private javax.swing.JButton btn_remove;
        private javax.swing.JButton btn_update;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel lbl_age;
        private javax.swing.JLabel lbl_gender;
        private javax.swing.JLabel lbl_name;
        private javax.swing.JTable table;
        private javax.swing.JTextField txt_age;
        private javax.swing.JTextField txt_gender;
        private javax.swing.JTextField txt_name;
        // End of variables declaration

    }

Q1.i saw many reviews to say

            public boolean isCellEditable ( int row, int column )
            {
                return editable;
            }

but how it utilize this in netbeans ?

Q2.Another review saw

      table.setEnabled(false);

but using this setting the entire row is disabled no row is selected individually?


Solution

  • In your initTables method, when you create an instance of the DefaultTableModel, just create an anonymous class and override the isCellEditable

    public void initTables() {
    
        dtm=new DefaultTableModel(0,0) {
            @Override
            public boolean isCellEditable(int row, int col) {
                return false;  // every cell is not editable
            }
        };
    
        dtm.addColumn("Name");
        dtm.addColumn("Age");
        dtm.addColumn("Gender"); 
    
    }