Java 如何设置行数?JTable setRowCount GUI 由 Jtextfield 和 JButton

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19628266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:55:49  来源:igfitidea点击:

How to set rowcount? JTable setRowCount GUI by Jtextfield and JButton

javaswingjtable

提问by Yefta Wahyu Saputra

I tried to create a table and manipulate it. but I do not understand what code should I write in my netbeans.

我试图创建一个表并对其进行操作。但我不明白应该在我的 netbeans 中编写什么代码。

JTextField1 variable n JButton1 Variable ok JTable1 Variable tabel1

JTextField1 变量 n JButton1 变量 ok JTable1 变量 tab1

on JButton1 or Ok Button I give code like this:

在 JButton1 或 Ok Button 上,我提供如下代码:

private void okActionPerformed(java.awt.event.ActionEvent evt) {
    int key = Integer.parseInt(n.getText());
    c.setText(String.valueOf(key));
    DefaultTableModel dtm = (DefaultTableModel) tabel1.getModel();
    for(int i = 0; i < key; i++){
    int r = tabel1.getRowCount()+1;
    dtm.setRowCount(r);
    }

}  

with code that I write, I managed to make the line corresponds to the number on JTextField1.

使用我编写的代码,我设法使该行与 JTextField1 上的数字相对应。

but when i press the ok button continuously. rows in the table continues to grow.

但是当我连续按下确定按钮时。表中的行继续增长。

how can i make that row in the table according to Jtextfield1 and no longer grow?

如何根据 Jtextfield1 在表中创建该行并且不再增长?

thanks before.

之前谢谢。

采纳答案by Thusitha Thilina Dayaratne

    DefaultTableModel dtm = (DefaultTableModel) tabel1.getModel();
    dtm.setRowCount(rowcount); // instead you can use your textfiled value here
e.g. dtm.setRowCount(Integer.parseInt((txtFieldName.getText()));
    tabel1.setModel(dtm);

回答by Yefta Wahyu Saputra

private void okActionPerformed(java.awt.event.ActionEvent evt) {                                   
    // TODO add your handling code here:
    int key = Integer.parseInt(n.getText());
    DefaultTableModel dtm = (DefaultTableModel) tabel1.getModel();
    dtm.setRowCount(0);
    for(int i = 0; i < key; i++){
    int r = tabel1.getRowCount()+1;
    dtm.setRowCount(r);
    }        
}