当焦点丢失时,JTable会丢失值

时间:2017-11-30 23:29:59

标签: java swing jtable tablemodel jxtreetable

我的JTable / JXTreeTable“忘记”刚输入的值,并在单元格焦点丢失时恢复默认值“Value x ”(通过单击另一个单元格,按Enter键等)。

我在SO上找到了一些建议,没有任何帮助。一个是设置putClientProperty(...),它没有改变任何东西。从: Can a Jtable save data whenever a cell loses focus?

我不知道为何这么困难。 请解释为什么输入的数据不会“粘住”以及如何修复它。

这是我的代码:

public class MyJTreeTable extends JXTreeTable{
public MyJTreeTable()
{
    setTreeTableModel(new MyTreeStructure(5));
    setRowSelectionAllowed(true);
    setDragEnabled(true);
    setEditable(true);
    setTreeCellRenderer(new DefaultTreeRenderer());
    setSelectionBackground(new Color(176, 197, 227));
    setSelectionForeground(new Color(0, 0, 128));
    BorderHighlighter border = new BorderHighlighter(new ColumnHighlightPredicate(1, 2), BorderFactory.createEmptyBorder(0, 6, 0, 6), false, false);
    addHighlighter(border);
putClientProperty("terminateEditOnFocusLost", true);

   addMouseListener(new java.awt.event.MouseAdapter() 
    {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) 
        {
            int row = rowAtPoint(evt.getPoint());
            int col = columnAtPoint(evt.getPoint());
            if (row >= 0 && col >= 0) 
            {
                editCellAt(row, 1);
                setSurrendersFocusOnKeystroke(true);
                getEditorComponent().requestFocus();

            }
         }
    });
}

    @Override
    public boolean isCellEditable(int row, int column) 
    {
        if (column == 1)
        {
            return true;
        }
        else return false;
    }
}

class MyTreeStructure extends DefaultTreeTableModel 
{

    DefaultMutableTreeTableNode Root = null;
    MyTreeStructure(int i) 
    {
        Root = new DefaultMutableTreeTableNode();

        this.setRoot(Root);
        for (int x = 0; x < 5; x++) 
        {
            DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode("HI");
            Root.add(node);
            for (int j = 0; j < i; j++) 
            {
                node.add(new DefaultMutableTreeTableNode(j));
            }
        }
    }

    @Override
    public String getColumnName(int column)
    {
        return "Value";
    }

    @Override
    public int getColumnCount() 
    {
        return 2;
    }

    @Override
    public Object getValueAt(Object arg0, int arg1) 
    {
        if (arg1 == 1) 
        {

            return new String("Value " + arg0.toString());
        }
    return arg0;
    }

}

0 个答案:

没有答案