【问题标题】:JTable last value nullJTable 最后一个值 null
【发布时间】:2019-07-10 12:39:07
【问题描述】:

我正在制作一个小游戏。所以现在我有一个只有 5 行的 JTable。

DefaultTableModel dtm = (DefaultTableModel) usernameTable.getModel();
dtm.setColumnCount(1);
dtm.setRowCount(5);

单击按钮后,我想保存表中的值。我的问题是最后一个值是每次 null

示例

表中的值:user1、user2、user3、user4、user5
预期输出:[user1, user2, user3, user4, user5]
输出:[user1, user2, user3, user4, null]

这就是我从表中获取数据的方式

ArrayList<String> username = new ArrayList<String>();

for (int i = 0; i < usernameTable.getRowCount(); i++) {
    username.add(usernamTable.getValueAt(i, 0);
}

可运行示例

public class JtableNullExample {
    private JTable usernameTable;
    private JPanel usernamePane;
    private JButton sendButton;
    private ArrayList<String> userList = new ArrayList<>();


    public static void main(String[] args) {
        new JtableNullExample();
    }

    public JtableNullExample() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //Setting Table Model
        DefaultTableModel dtm = (DefaultTableModel) usernameTable.getModel();
        dtm.setColumnCount(1);
        dtm.setRowCount(5);

        frame.setContentPane(usernamePane);
        frame.setVisible(true);

        sendButton.addActionListener(e -> {

            for (int count = 0; count < usernameTable.getRowCount(); count++) {

                System.out.println(usernameTable.getValueAt(count, 0));
                userList.add(usernameTable.getValueAt(count, 0).toString());
            }

        });
    }
}

【问题讨论】:

  • 您发布的代码没有给我们任何有关问题的提示。请创建一个小型可运行类 (minimal reproducible example) 来演示您的问题。在这种情况下,我们也可以对其进行调试,以提供适合您代码的解决方案。
  • @SergiyMedvynskyy 我更新了我的问题。但我想我已经找到了解决办法。 (看我的解决方案)

标签: java swing jtable


【解决方案1】:

好的,我找到了解决方案。 问题是,JTable 不知道我们是否完成了对单元格的编辑。

if (usernameTable.isEditing()) {
   usernameTable.getCellEditor().stopCellEditing();
}

这将停止编辑单元格,现在您不应再获得任何空值。

解决方案:
https://tips4java.wordpress.com/2008/12/12/table-stop-editing/

Jtable not returning the last cell value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多