如何在 Java 中从二维数组创建 JTable?
对于二维数组,设置一个表的列。此外,我们已经使用一个一维数组设置了行,如下所示 −
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);
下面是通过二维数组创建表的示例 −
示例
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); } }
这将产生以下输出 −
广告