我尝试启动一个" JTable",我通过表单设计器添加了所有元素,并在GUI的main函数中启动它们。
该表位于" 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);
}
}
答案 0 :(得分:1)
frame.setLayout(new SpringLayout());
....
frame.add(insertedFilesViewport);
不要将框架的布局更改为SpringLayout。没有理由这样做。
您没有看到包含该表的滚动窗格的原因是您没有对add(...)方法使用任何约束。阅读How to Use SpringLayout上Swing教程中的部分,了解添加组件的约束有多复杂。
如果您将布局保留为默认BorderLayout
,则默认情况下,该组件将添加到CENTER
的{{1}}。上面的教程还有一个关于你应该阅读BorderLayout
的部分。