Java Swing How to - Show JTable Column using JScrollPane








Question

We would like to know how to show JTable Column using JScrollPane.

Answer

// w ww.ja v a2  s  .co  m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Main {
  public static void main(String args[]) {
    String[] columnNames = { "Date", "Field", "Home Team", "Visitor Team",
        "Score" };
    JFrame guiFrame = new JFrame();
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setSize(500, 500);

    JPanel panel = new JPanel();
    panel.setSize(450, 450);
    JLabel titleLabel = new JLabel("OK");
    String[][] data = new String[0][0];
    JTable scheduleTable = new JTable(data, columnNames);
    JScrollPane scrollPane = new JScrollPane(scheduleTable);
    panel.add(scrollPane);
    panel.add(titleLabel);

    guiFrame.add(panel);
    guiFrame.setVisible(true);
  }
}