
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create DefaultTableModel from Two-Dimensional Array in Java
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
Advertisements