Java 程序根据二维数组创建 DefaultTableModel
DefaultTableModel 是 TableModel 的一个实现,它使用一个 Vectors 对容器来存储单元格的 value 对象。首先创建一个二维数组,以用于行和列 -
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 -
JTable table = new JTable(tableModel);
以下是如何根据二维数组创建 DefaultTableModel 的例子 -
例子
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); } }
输出
广告