0

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);

            }
        };
    }
kleopatra
  • 51,061
  • 28
  • 99
  • 211
jwm197
  • 79
  • 8
  • 1
    Your requirement makes no sense to me. You populate the table with data greater than 1 character in length. Why would you only save the last character typed by the user if they attempt to change it? If we know the reason for this strange requirement we can probably suggest a better solution. For example you might use a custom editor that only accepts a single character. – camickr Aug 13 '22 at 15:15
  • 1
    You might get some ideas from the key-event editor cited [here](https://stackoverflow.com/a/6366456/230513). – trashgod Aug 13 '22 at 16:27
  • Effectively I am trying to keep only the last character but I want the user to be able to see what they have typed while typing. – jwm197 Aug 13 '22 at 21:38

1 Answers1

0

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);

            }
jwm197
  • 79
  • 8