Home > Blockchain >  How do I set the value of a cell in a Jtable to be only the last character entered when clicking off
How do I set the value of a cell in a Jtable to be only the last character entered when clicking off

Time:08-16

I am trying to make it so that when the user clicks off the cell they are editing in a JTable the contents of the cell is set only to the last character entered. To achieve this I have a method that returns a new JTable with an anonymous class overriding the editingStopped method. Right now this is producing 2 errors: The first being that it won't display the updated string in the cell and secondly the lastChar variable is being set to the last character that was in the cell prior to the cell being click on. Here is my code:

 private JTable makeTable() {
        String data[][] = { 
                { "Move Down", "hello" }};
        String[] headers = { "Action", "Button" };
        return new JTable(new DefaultTableModel(data, headers)) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 1;
            }

            public void editingStopped(ChangeEvent e) {
                String lastChar = getValueAt(getEditingRow(), 1).toString().substring(
                        getValueAt(getEditingRow(), 1).toString().length() - 1);
                        setValueAt(lastChar, getEditingRow(), 1);
                System.out.println("Row "   (getEditingRow())   " edited");
                System.out.println("Cell set to:"   lastChar);

            }
        };
    }

CodePudding user response:

This can be solved with calling the super method as it wasn't leaving the cell properly creating issues.

public void editingStopped(ChangeEvent e) {
                int row=getEditingRow();
                System.out.println("Row "   (getEditingRow())   " edited");
                super.editingStopped(e);
                
                String lastChar = getValueAt(row, 1).toString().substring(
                        getValueAt(row, 1).toString().length() - 1);
                setValueAt(lastChar, row, 1);
                System.out.println("Cell set to:"   lastChar);

            }
  • Related