我的问题是如何动态设置JTable中的行数和列数?我的意思是,如果用户想要创建一个 2 行 2 列的表格,他只需键入数字即可。我该怎么做,我尝试使用 DefaultModel 但没有成功。
我将不胜感激。
谢谢
最佳答案
DefaultTableModel
有两种方法可以在运行时定义行数/列数。
你可以...
只需创建一个新的 DefaultTableModel
,将您想要的行和列传递给它...
DefaultTableModel model = new DefaultTableModel(rows, cols);
然后将其应用于 JTable
。显然,这将替换现有的表模型,这意味着您将丢失其中的所有数据。
你可以...
创建一个主控 DefaultTableModel
并将其应用到 JTable
并简单地使用
model.setRowCount(rows);
model.setColumnCount(cols);
根据需要动态更新行数和列数。这将允许您保留表模型中的数据(预计当您删除行或列时,它会丢失)
可运行的例子
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
private DefaultTableModel model;
private JSpinner fldRows;
private JSpinner fldColumns;
public TestPane() {
setLayout(new BorderLayout());
fldRows = new JSpinner(new SpinnerNumberModel(1, 1, 999999, 1));
fldColumns = new JSpinner(new SpinnerNumberModel(1, 1, 999999, 1));
JPanel options = new JPanel(new GridBagLayout());
options.add(new JLabel("Rows: "));
options.add(fldRows);
options.add(new JLabel("Columns: "));
options.add(fldColumns);
JButton update = new JButton("Update");
options.add(update);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rows = (int) fldRows.getValue();
int cols = (int) fldColumns.getValue();
// Dynamic master model...
// model.setRowCount(rows);
// model.setColumnCount(cols);
// Replace model
table.setModel(new DefaultTableModel(rows, cols));
}
});
model = new DefaultTableModel();
table = new JTable();
add(new JScrollPane(table));
add(options, BorderLayout.NORTH);
}
}
}
更多细节,见...
关于java - 如何设置 JTable Dynamic 的行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26982622/