简体   繁体   English

JTable swing ID迭代器

[英]JTable swing ID iterator

I am new on Swing Java. 我是Swing Java的新手。 I have a JTable which has 3 columns (ID, state, age), I have a form with 2 JTextField and a JButton, when I click the button, a row will be added to my JTable but I want the ID to be iterated by 1, for example when I click the first time the Id is 0, when I click another time with new data entered the Id wil become 1 (0+1). 我有一个JTable,它有3列(ID,状态,年龄),我有一个带有2个JTextField和一个JButton的表单,当我点击按钮时,一行将被添加到我的JTable但我希望ID被迭代1,例如当我第一次点击Id为0时,当我点击另一个时间输入新数据时,Id将变为1(0 + 1)。 There's any function to get the value of the cell in the last row in column 0? 有没有任何函数可以获取第0列最后一行中单元格的值? And how to initialise the Id if the JTable is empty for the first run? 如果JTable在第一次运行时为空,如何初始化Id? Here's my source code 这是我的源代码

String[] columnNames = { "ID", "state", "age" };

    int[] columnsWidth = { 188, 500, 100 };
    table = new JTable(
            new DefaultTableModel(new Object[][] {}, columnNames));
 JScrollPane scrollPane = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    tableau.setLayout(new BorderLayout());
    tableau.add(scrollPane, BorderLayout.CENTER);

    logaffich.add(tableau);

Code for the button 按钮的代码

  boutonround.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
DefaultTableModel tm = (DefaultTableModel) table.getModel();

            String numcam = age.getText();
            // Int c=0;
            String desc = display.getSelectedItem().toString();

            tm.addRow(new Object[] { new String(c), new String(desc),
                    new String(numcam) });
            table.setModel(tm);}

You can get an ID that is one more than the last row, and 0 if there are no rows, by just doing this: 您可以获得一个比最后一行多一个的ID,如果没有行,则可以获得0,只需执行以下操作:

int value = tm.getRowCount() == 0 ? 0 : 
    Integer.parseInt((String)tm.getValueAt(tm.getRowCount() - 1, 0)) + 1;

Also, there is no need to do table.setModel(tm) ; 此外,没有必要做table.setModel(tm) ; the table model automatically updates the table when changes are made. 进行更改时,表模型会自动更新表。

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

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