Java Program to create DefaultTableModel from two dimensional array

Java 8Object Oriented ProgrammingProgramming

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

raja
Published on 04-Jun-2019 08:26:06
Advertisements