Java Swing How to - Load multidimensional array into JTable








Question

We would like to know how to load multidimensional array into JTable.

Answer

import java.awt.BorderLayout;
/* w  w  w .  j av a  2  s. co m*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    Integer[][] board = { 
        { 1, 1, 1, 1, 2, 0, 0, 0, 0 },
        { 0, 0, 5, 0, 1, 0, 0, 2, 4 }, 
        { 1, 0, 0, 4, 0, 0, 0, 3, 8 },
        { 0, 0, 0, 6, 1, 0, 0, 3, 7 },
        { 0, 0, 4, 5, 3, 8, 9, 4, 0 },
        { 8, 0, 0, 0, 1, 7, 0, 4, 0 },
        { 7, 4, 0, 0, 1, 6, 0, 3, 1 },
        { 6, 1, 0, 0, 1, 0, 3, 3, 0 },
        { 0, 0, 0, 0, 1, 1, 1, 1, 0 } };

    String col[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
    JTable table = new JTable(board, col);
    panel.add(table, BorderLayout.CENTER);

    frame.add(panel);
    frame.setSize(800, 500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}