簡體   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