Java Program to create DefaultTableModel from two dimensional array


The DefaultTableModel is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects. At first create a two dimensional array for rows and columns −

DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {
   { "India", "Asia" }, { "Canada", "North America" }, { "Singapore", "Asia" },
   { "Malaysia", "Asia" }, { "Philippins", "Asia" }, { "Oman", "Asia" },
   { "Germany", "Europe" }, { "France", "Europe" }
 },
new Object[] { "Country", "Continent" });

Above, “Country” and “Continent” are the columns. Now, set the above set of rows and columns to JTable −

JTable table = new JTable(tableModel);

The following is an example to create DefaultTableModel from two dimensional array −

Example

package my;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {
         { "India", "Asia" }, { "Canada", "North America" }, { "Singapore", "Asia" },
         { "Malaysia", "Asia" }, { "Philippins", "Asia" }, { "Oman", "Asia" },
         { "Germany", "Europe" }, { "France", "Europe" }
      },
      new Object[] { "Country", "Continent" });
      JTable table = new JTable(tableModel);
      Font font = new Font("Verdana", Font.PLAIN, 12);
      table.setFont(font);
      table.setRowHeight(30);
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements