繁体   English   中英

如何将 Jtable 中的单元格的值设置为仅在单击它时输入的最后一个字符?

[英]How do I set the value of a cell in a Jtable to be only the last character entered when clicking off of it?

我正在尝试这样做,以便当用户单击他们在 JTable 中编辑的单元格时,单元格的内容仅设置为输入的最后一个字符。 为了实现这一点,我有一个方法返回一个新的 JTable ,其中匿名 class 覆盖了 editingStopped 方法。 现在这会产生 2 个错误:第一个是它不会在单元格中显示更新的字符串,第二个是 lastChar 变量被设置为在单击单元格之前单元格中的最后一个字符。 这是我的代码:

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

            }
        };
    }

这可以通过调用 super 方法来解决,因为它没有正确地离开单元格,从而产生问题。

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

            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM