Java Swing How to - Add a title to a JTable








Question

We would like to know how to add a title to a JTable.

Answer

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
//from   ww w .  jav  a2  s. co  m
public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createTitledBorder(
        BorderFactory.createEtchedBorder(), "Table Title", TitledBorder.CENTER,
        TitledBorder.TOP));

    JTable table = new JTable(3, 3);

    panel.add(new JScrollPane(table));

    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}