Java Swing How to - Set column name when creating JTable








Question

We would like to know how to set column name when creating JTable.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/*w w  w .  j a v  a 2  s .  c  om*/
public class Main extends JFrame {

  public Main() {
    setSize(600, 300);
    String[] columnNames = { "A", "B", "C" };
    Object[][] data = { { "M", "a", 2 }, { "J", "e", 4 }, { "M", "z", 6 } };

    JTable table = new JTable(data, columnNames);
    JScrollPane tableSP = new JScrollPane(table);

    add(tableSP);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
    new Main().setVisible(true);

  }
}