Java Swing How to - Convert Arraylist to 2D array and then fill to JTable








Question

We would like to know how to convert Arraylist to 2D array and then fill to JTable.

Answer

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
//  w w w  .ja  v a  2 s .  c  o  m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

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

class Test extends JFrame {
  String[] name = { "Name", "grade" };
  Object[][] cells = { { "A", "B" }, { "C", "D" }, { "E", "F" } };

  public Test() {
    setSize(500, 210);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTable tabell = new JTable(cells, name);

    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    c.add(new JScrollPane(tabell), BorderLayout.CENTER);
  }
}