Java JTable class

Introduction

The JTable class lets us create a tabular grid of data.

For example, the following program creates a table of 4 rows and 2 columns.

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Main {
   public static void main(String args[]) {
      JFrame f = new JFrame("JTable Demo");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();

      f.setSize(200, 120);/*  w w  w. j av a  2 s.  c o m*/
      f.setLayout(new FlowLayout());
      int row = 4, col = 2;
      JTable table = new JTable(row, col);
      for (int i = 0; i < row; i++) {
         table.setValueAt(i, i, 0);
         table.setValueAt(i * i, i, 1);
      }
      c.add(new JScrollPane(table));
      f.setVisible(true);
   }
}



PreviousNext

Related