简体   繁体   English

通过未完成的编辑关闭其JFrame时保存JTable的内容

[英]save JTable's contents when closing its JFrame with unfinished editing

I am having the following issue: I have a JTable with its on tablemodel sitting on a JFrame. 我遇到以下问题:我有一个JTable及其JTable上的on tablemodel。 The tablemodel is backed up with an own hashmap to store the contents. tablemodel用自己的hashmap备份以存储内容。 The table has two columns where the right one is editable. 该表有两列,其中右列是可编辑的。

Normally the user changes some value on the right then presses the enter button which fires the tabledatachanged event that calls my saving function. 通常,用户会在右侧更改一些值,然后按Enter键,这会触发tabledatachanged事件,该事件调用我的保存功能。 Then the frame can be closed. 然后可以关闭框架。

However, some users just simply edit the cell and then they close the window without pressing enter so I get no chance to save the table. 但是,有些用户只是简单地编辑单元格,然后关闭窗口而不按Enter键,因此我没有机会保存表格。 I know how to write events when the frame is about to be closed, but I do not know how to retrieve the content of the "unfinished" editing while also finalizing that edit. 我知道在框架即将关闭时如何编写事件,但是我不知道如何在完成编辑的同时检索“未完成”编辑的内容。

I guess it has something to do with the celleditors, I even tried with the table.getCellEditor() that should return the active one but instead it returns null. 我猜想它与celleditors有关,我什至尝试了table.getCellEditor()应该返回活动的那个,但它返回null。

Thanks for the help! 谢谢您的帮助!

The most simple measure is to configure the table to do its best effort when loosing focus: 最简单的措施是配置表以使其在失去焦点时尽力而为:

table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

Unfortunately, there are contexts when its best effort is not good enough (fi when the user clicks the close button of a frame). 不幸的是,在某些情况下,其尽力而为还不够好(例如,当用户单击框架的关闭按钮时,fi就会出现)。 In those, there is no way but to hook into each and every lane that might loose the edit and manually force the edit to stop 在那种情况下,除了陷入可能使编辑松散并手动强制停止编辑的每个通道之外,别无他法

if (table.isEditing()) {
    boolean stopped = table.getCellEditor().stopCellEditing();
    if (!stopped) {
        // here goes error handling and/or cancelling the edit
    }
}

From your description of the problem, 根据您对问题的描述,

some users just simply edit the cell and then they close the window without pressing enter 一些用户只是简单地编辑单元格,然后关闭窗口而无需按Enter

I'm slightly surprised the the first is working, would have expected that you needed doing the second in a WindowListener. 我微微一愣的第一个工作 ,本来期望你需要做的的WindowListener第二。

See also Rob's blog entry 另请参阅Rob的博客条目

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

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