How to create JTable from two dimensional array in Java?

Java 8Object Oriented ProgrammingProgramming

With two dimensional array, set the columns of a table. Additionally, we have set the rows using a one-dimensional array as shown below −

DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {
   { "Mobile Phones", "100" }, { "RAM", "200" }, { "Caps", "50" },
   { "Tablet", "80" }, { "LED", "400" }, { "Trousers", "350" },
   { "T-Shirt", "500" }, { "Hoodie", "650" }, { "Jeans", "900" } },
   new Object[] { "Items", "Quantity" }
);

Now set the table model to the table −

JTable table = new JTable(tableModel);

The following is an example to create a table 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[][] {
         { "Mobile Phones", "100" }, { "RAM", "200" }, { "Caps", "50" },
         { "Tablet", "80" }, { "LED", "400" }, { "Trousers", "350" },
         { "T-Shirt", "500" }, { "Hoodie", "650" }, { "Jeans", "900" } },
         new Object[] { "Items", "Quantity" }
      );
      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);
   }
}

This will produce the following output −

raja
Published on 03-Jun-2019 08:51:55
Advertisements