慕森卡
有多种方法可以在 中添加/删除数据。下面的程序演示了 和 的用法。JTableaddRow()setModel()请注意,方法仅在 中存在。因此,当您使用其他表模型时,必须使用不同的方法。addRow()DefaultTableModelimport javax.swing.*;import javax.swing.table.DefaultTableModel;import java.awt.BorderLayout;import java.awt.event.*;public class PopulateTable{ public static void main(String[] args) { JTable table = new JTable(); table.setModel(new DefaultTableModel( new Object[][] { }, new String[] { "Location", "Latitude", "Longitude", "Nitrogen", "Phosphorus", "Potassium", "pH" } )); JButton button1 = new JButton("Add First Row"); button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ((DefaultTableModel) table.getModel()).addRow(Data.getFirstRow()); } }); JButton button2 = new JButton("Set All Rows"); button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { table.setModel(new DefaultTableModel( Data.getAllRows(), new String[] { "Location", "Latitude", "Longitude", "Nitrogen", "Phosphorus", "Potassium", "pH" } )); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(button1); buttonPanel.add(button2); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER); frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); }}class Data{ private static Object[][] rows = new Object[][] { {"a1", "b1", "c1", "d1", "e1", "f1", "g1"}, {"a2", "b2", "c2", "d2", "e2", "f2", "g2"}, {"a3", "b3", "c3", "d3", "e3", "f3", "g3"}, {"a4", "b4", "c4", "d4", "e4", "f4", "g4"} }; static Object[][] getAllRows() { return rows; } static Object[] getFirstRow() { return rows[0]; }}