Java Swing How to - Get value of Last cell in JTable








Question

We would like to know how to get value of Last cell in JTable.

Answer

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from   ww w.j ava  2 s.  co m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;

public class Main extends JFrame implements ActionListener {
  JTable table;
  JButton button;
  public Main() {
    String[] colNames = { "Subject", "Value" };
    String[][] rowDatas = { { "Java", "Jon" },
        { "C++", "Hard" }, { "Math", "Mike" },
        { "Database", "Sql" } };
    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 Main();
  }
}