Can't edit my JTable data with setValueAt()

can definition
can synonym
can verb
can noun meaning
can bus
can airport
can network
can band

After spending my afternoon trying to find a solution, I finally created an account to ask my question and I hope someone can help me.

I'm creating a JTable in an internal frame. I have my own tableModel and cellRenderer (because i want the user to be able to edit only the cells of the borders of the table, and I want the uneditable cells to be grey). It works fine, the uneditable cells are grey and we can't clic on it. The others, we can clic on it BUT when we modify the value and press enter, nothing happen, the value get back to default. I tried to modify the cell value in the code with the "setValueAt()" method but i doesn't work either.

I tried to implement some listener but nothing worked :/. Can you help me please? I hope I'm clear enough. Here's my code to help:

MyCellRenderer.java (working perfectly)

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class MyCellRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column){
        if (table.isCellEditable(row, column)) {
           setBackground(Color.white);
        }
        else {
           setBackground(Color.darkGray);
        }

        return super.getTableCellRendererComponent(table, value, isSelected,
                                                   hasFocus, row, column);
   }
}

MyTableModel.java (working perfectly)

import javax.swing.table.DefaultTableModel;

public class MyTableModel extends DefaultTableModel{
    public boolean[][] canEdit = new boolean[][]{};

    public void setEditModel(int maxRow, int maxCol){
        canEdit = new boolean[maxRow][maxCol];
        for(int col=0;col< maxCol; col++){
            for(int row=0;row< maxRow; row++){
                if(col == 0 || row == 0 || col == maxCol-1){
                    canEdit[row][col] = true;
                }
                else{
                    canEdit[row][col] = false;
                }
            }
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit[rowIndex][columnIndex];
    }
}

Here's a part of my main frame. When I press this Button, it create the table in the internal frame

private void jButtonValiderTailleCuisineActionPerformed(java.awt.event.ActionEvent evt) {                                                            

    MyTableModel dataModel;
    dataModel = new MyTableModel() {
            @Override public int getColumnCount() { return jSliderLongueur.getValue(); }
            @Override public int getRowCount() { return jSliderLargeur.getValue();}
            @Override public Object getValueAt(int row, int col) { return 0; }
        };
        table = new JTable(dataModel);
        dataModel.setEditModel(jSliderLargeur.getValue(), jSliderLongueur.getValue());
        table.setDragEnabled(false);
        table.setTableHeader(null);
        table.setCellSelectionEnabled(true);
        table.setRowSelectionAllowed(false);
        table.setColumnSelectionAllowed(false);
        table.setRowHeight(40);
        TableColumn column;
        for (int i = 0; i < jSliderLongueur.getValue(); i++) {
            column = table.getColumnModel().getColumn(i);
            column.setMinWidth(40);
            column.setMaxWidth(40);
        }
        System.out.println(dataModel.getValueAt(5, 5));

        JPanel m_rootPanel = new JPanel();
        JScrollPane jScrollPane1 = new JScrollPane(table);
        m_rootPanel.setLayout(new BorderLayout());
        jInternalFramePourTableau.setContentPane(m_rootPanel);
        m_rootPanel.add(jScrollPane1, BorderLayout.CENTER);

        for (int i =0; i<dataModel.getColumnCount();i++) {
            table.setDefaultRenderer(table.getColumnClass(i), new MyCellRenderer());
        }

        table.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            int row = table.rowAtPoint(evt.getPoint());
            int col = table.columnAtPoint(evt.getPoint());
            if (row >= 0 && col >= 0) {
                selectedCell[0] = row;
                selectedCell[1] = col;
                System.out.println("Vous avez cliquez en: " + selectedCell[0] + " " + selectedCell[1]);
            }
        }
    });

        jSliderLongueur.setEnabled(false);
        jSliderLargeur.setEnabled(false);
        jButtonValiderTailleCuisine.setEnabled(false);
}

It works, but I can't edit the cells which are not grey. So the problem is maybe the way I create my table.

Here's my not working code (it's when i press this button, It must change the value of the selected cell with the value "TEST"):

private void jButtonChangeValueActionPerformed(java.awt.event.ActionEvent evt) {                                                
        System.out.println("CurrentCellSelected: " + selectedCell[0] + " " + selectedCell[1]);//it is the correct selectedCell
        dataModel.setValueAt("TEST", selectedCell[0], selectedCell[1]);//NOT WORKING
    } 

When I clicked the button "jButtonChangeValueActionPerformed", the line dataModel.setValueAt(...) does nothing.

I really hope someone can help me, I wasted so much time trying to find a solution.

Good evening everyone.

The following piece of code is missing in your code:

table.getModel().addTableModelListener(new TableModelListener() {
    public void tableChanged(TableModelEvent e) {
        table.setValueAt("TEST", selectedCell[0], selectedCell[1]);
    }
});

Add it just after table = new JTable(dataModel); so that it will remain close to the table instantiation making it easier for you to find it when you update your code.

Can, Can was the leading avant-garde rock group of the 70s. Can experimented with noise, synthesizers, non-traditional music, cut-and-paste techniques, and, most� Can definition, to be able to; have the ability, power, or skill to: She can solve the problem easily, I'm sure. See more.

Ok I added that:

table.getModel().addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {

            table.getModel().removeTableModelListener(this);
            System.out.println("TABLE CHANGED");
            table.setValueAt("TEST", selectedCell[0], selectedCell[1]);
            table.getModel().addTableModelListener(this);
        }
    });

and now it call this method just once. But it doesn't resolve my problem, the data is still unmodifiable.

I assume that the problem is the method setValueAt(). This method, wherever I call it, doesn't work. I don't know I have to override it like I overrided TableModel. Or if I have to call some redraw-table method?

EDIT: I tried to override the setValueAt() method but it's useless, like I was thinking...

import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class MyTableModel extends DefaultTableModel{
    public boolean[][] canEdit = new boolean[][]{
        /*{true, true, true, true, true, true},
        {true, false, false, false, false, true},
        {true, false, false, false, false, true},
        {true, false, false, false, false, true},
        {true, false, false, false, false, true},
        {true, false, false, false, false, true}*/
    };
        TableModel model;

    public void setEditModel(int maxRow, int maxCol){
        canEdit = new boolean[maxRow][maxCol];
        for(int col=0;col< maxCol; col++){
            for(int row=0;row< maxRow; row++){
                if(col == 0 || row == 0 || col == maxCol-1){
                    canEdit[row][col] = true;
                }
                else{
                    canEdit[row][col] = false;
                }
            }
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit[rowIndex][columnIndex];
    }
    //useless override cause it's the same definition in DefaultTableModel
    @Override
    public void setValueAt(Object value, int row, int column) 
    {
        ((Vector) dataVector.get(row)).set(column, value);
        fireTableCellUpdated(row, column);
    }
}

Can, VerbEdit. can (third-person singular simple present can, present participle -, simple past could, past participle (obsolete except in adjectival use) couth). Define can. can synonyms, can pronunciation, can translation, English dictionary definition of can. to be able to, have the power or skill to: I can take a bus to the

Ok I solved it. I just commented the line:

        //public Object getValueAt(String value, int row, int col) { return value; }

in my main frame class, where I create my JTable, and now it works fine!

In conclusion: Overriding the method "getValueAt()" set the method "setValueAt()" unusable. (in my case).

dataModel = new MyTableModel() {
            @Override public int getColumnCount() { return jSliderLongueur.getValue(); }
            @Override public int getRowCount() { return jSliderLargeur.getValue();}
            //public Object getValueAt(String value, int row, int col) { return value; }
        };

The Official CAN / Spoon Records Website, 1.4Used to indicate that something is typically the case. 'antique clocks can seem out of place in modern homes'. More example sentences. can definition: 1. to be able to: 2. used to say that you can and will do something: 3. to be allowed to: . Learn more.

can, can noun [C] (CONTAINER). a metal container, esp. a closed, cylindrical container in which food and drink are packaged:. 110 synonyms of can from the Merriam-Webster Thesaurus, plus 97 related words, definitions, and antonyms. Find another word for can. Can: to bring (as an action or operation) to an immediate end.

Can, Word forms � 1. countable noun A can is a metal container in which something such as food, drink, or paint is put. � 2. verb [usually passive] When food or drink is� Can (stylised as CAN) was a German experimental rock band formed in Cologne in 1968 by the core quartet of Holger Czukay (bass, tape editing), Irmin Schmidt (keyboards), Michael Karoli (guitar), and Jaki Liebezeit (drums).

CAN, can 2. (kăn). n. 1. A usually cylindrical metal container. 2. Find the latest Canaan Inc. (CAN) stock quote, history, news and other vital information to help you with your stock trading and investing.

Comments
  • jButtonChangeValueActionPerformed() isn't a button, it's a method. You need to add an ActionListener to your button with a proper actionPerformed() method. It doesn't seem like you've included to code where you create your button, though, so I'm not sure exactly what that would look like.
  • @azurefrog Yeah I misswrite that, but it's not the problem, i want to change the value when the action is performed, it's linked to a jComboBox but I simplify that part cause it's not important. Thank you anyway!
  • @ArvindKumarAvinash in my button method, under the table creation. But the problem isn't the listener. The problem is the fact that table.setValueAt() is not working.