java - Jtable 未加载

标签 java swing jtable

我尝试启动一个“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);
    }
}

My result

最佳答案

frame.setLayout(new SpringLayout());

....

frame.add(insertedFilesViewport);

不要将框架的布局更改为 SpringLayout。没有理由这样做。

您看不到包含该表的滚动 Pane 的原因是您没有对 add(...) 方法使用任何约束。阅读 Swing 教程中关于 How to Use SpringLayout 的部分看看添加组件的约束有多复杂。

如果您将布局保留为默认的 BorderLayout,则该组件将默认添加到 BorderLayoutCENTER 中。上面的教程还有一个关于如何使用 BorderLayout 的部分,您应该阅读。

关于java - Jtable 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42627151/

相关文章:

Java(仅限 Windows 问题): alwaysOnTop JFrame falls to bottom of z-order when modal dialog is popped and blocked JFrames are clicked

java - 处理自己滚动的 JTabel 替代方案

java - 当 SQL 进行排序时,如何启用 GUI 行为来对 JTable 进行排序?

java - 根据Java中另一个arraylist中的对象值对arraylist进行排序

Java WebApp 和 tomcat context.xml

ArrayList 中的 Java 排序对象

java - 更大的 TextField Java 中的更小的 TextField

java - 如何将 Java 2D Shape 对象序列化为 XML?

java - JTable 自动滚动方法一行太高

java - 给 JEditorPane 一个像 JTextArea 一样的 append(...) 方法