0

我有一个查询...代码运行良好,但无法获取最后一行和最后一列的最后一个单元格的值。以下是代码...请指导

使用此代码将行动态添加到 JTable : if(e.getSource()==addb) {

        model.addRow(new Object[3]);
        repaint();

    }

下面是从 JTable 逐行获取值的代码,稍后将代替 System.out.println() 将数据发送到数据库...

if(e.getSource()==submit)
    {
        int j = table.getRowCount();
        for(int row=1;row<j;row++)
        {
            for(int column=0;column<3;column++)
            {
                System.out.println("row  "+row+"   Column is  "+column);                    
                System.out.println(model.getValueAt(row, column));
            }
        }

    }
4

3 回答 3

3

像这样的东西:

int i= table1.getRowCount()-1;
int j= table1.getColumnCount();
Object [] value = new Object[j];
for(int k = 0 ; k<j ; k++)
{
value[k] = model.getValueAt(i,k);
}   

另见这个小例子

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TableTest extends JFrame implements ActionListener{

    JTable table ;
    JButton button;
    public TableTest(){
        String []colNames = {"Subject","lecturer"}; 
        String [][] rowDatas = { {"Java Programming","Jon"},
                                 {"C++ Programming","Nuhara"},
                                 {"Mathematicz","Mike"},
                                 {"Database","Saran"}
                                };
        table = new JTable(rowDatas,colNames);

        button = new JButton("Show Last Record");
        button.addActionListener(this);

        this.add(table);
        this.add(button);
        this.setVisible(true);
        this.setSize(300,200);
        this.setDefaultCloseOperation(3);
        this.setLayout(new FlowLayout());
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        int i= table.getRowCount()-1;
        int j= table.getColumnCount();
        Object [] value = new Object[j];
        for(int k = 0 ; k<j ; k++)
        {
        //value[k] = table.getValueAt(i,k);
            System.out.println(table.getValueAt(i, k));
        }  
    }


    public static void main(String...ag){
        new TableTest();
    }
}
于 2013-02-23T15:38:40.990 回答
2

当您单击“提交”按钮时,疯狂地猜测您正在编辑最后一个单元格。

如果是这样,请参阅:表格停止编辑

于 2013-02-23T17:21:05.117 回答
0

谢谢阿扎德,
它现在工作得很好......
我稍微编辑了代码以从所有行中获取数据......

 int i= table.getRowCount()-1;
        int j= table.getColumnCount();

        for (int d=1;d<i+1;d++){   // will provide row wise data
        for(int k = 0 ; k<j ; k++)  // will provide column wise data
        {
          System.out.println("row num   "+d+"   "+model.getValueAt(d,k));
        }   }
于 2013-03-02T03:21:21.540 回答