如何在JTable中获取Last cell的值?

时间:2013-02-23 15:27:55

标签: java swing jtable tablemodel

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

使用此代码将动态添加到JTable:     如果(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));
            }
        }

    }

3 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:2)

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

如果是,请参阅:Table Stop Editing

答案 2 :(得分:0)

谢谢Azad,
它的工作精湛现在......
我有一点编辑代码来从所有行获取数据......

 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));
        }   }