我尝试启动一个“JTable”,我通过表单设计器添加了所有元素,并在 GUI 的主要功能中启动了它们。
表格放置在“JScrollPanel”内,并使用“DefaultTableModel”添加标题和行。
无论我做什么,我都无法使表格显示标题或行。
我在这里缺少什么?
class Controls extends JPanel{
private JButton compileButton;
private JPanel controls;
private JTabbedPane tabbedPane1;
private JButton insertButton;
private JTable insertedFilesTable;
private JScrollPane insertedFilesViewport;
private JPanel minify;
private JFileChooser insertChooser;
public Controls () {
insertChooser = new JFileChooser();
compileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
initCompile();
}
});
insertButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
buttonActionPerformed(e);
}
});
}
public void main () {
JFrame frame = new JFrame("Controls");
frame.setLayout(new SpringLayout());
frame.setContentPane(new Controls().controls);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Files");
model.addColumn("Status");
insertedFilesTable = new JTable(model);
insertedFilesViewport = new JScrollPane(insertedFilesTable);
insertedFilesViewport.setViewportView(insertedFilesTable);
insertedFilesTable.setFillsViewportHeight(true);
String[] data = {"test","test"};
model.addRow(data);
frame.add(insertedFilesViewport);
frame.setSize(500,500);
frame.setVisible(true);
}
private void buttonActionPerformed(ActionEvent evt) {
insertChooser.showSaveDialog(this);
}
}
最佳答案
frame.setLayout(new SpringLayout());
....
frame.add(insertedFilesViewport);
不要将框架的布局更改为 SpringLayout。没有理由这样做。
您看不到包含该表的滚动 Pane 的原因是您没有对 add(...) 方法使用任何约束。阅读 Swing 教程中关于 How to Use SpringLayout 的部分看看添加组件的约束有多复杂。
如果您将布局保留为默认的 BorderLayout
,则该组件将默认添加到 BorderLayout
的 CENTER
中。上面的教程还有一个关于如何使用 BorderLayout
的部分,您应该阅读。
关于java - Jtable 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42627151/