如何使用 Java 在 JPanel 中显示 JTable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2623957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:01:21  来源:igfitidea点击:

How to display a JTable in a JPanel with Java?

javaswingjtablejpanel

提问by Eddinho

How to display a JTable in a JPanel with Java?

如何使用 Java 在 JPanel 中显示 JTable?

采纳答案by justkt

Imports and table model left as an exercise to the user of this code. Also, the panel layout is arbitrarily chosen for simplicity.

导入和表模型留给此代码的用户作为练习。此外,为了简单起见,面板布局是任意选择的。

public class JTableDisplay {
    public JTableDisplay() {
        JFrame frame = new JFrame("JTable Test Display");

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        JTable table = new JTable();

        JScrollPane tableContainer = new JScrollPane(table);

        panel.add(tableContainer, BorderLayout.CENTER);
        frame.getContentPane().add(panel);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new JTableDisplay();
    }
}

The scroll pane is fairly important to note. Without it, your table won't have a header or scroll if the content becomes larger than the display.

滚动窗格非常重要。没有它,如果内容大于显示,您的表格将没有标题或滚动条。

回答by Hyman

JTable table = new JTable();
JScrollPane spTable = new JScrollPane(table);
JPanel panel = new JPanel();

panel.add(spTable);

There is a comphrensive guide about how to layout swing components, you should consider Pyrolistical link..

有一个关于如何布局摆动组件的综合指南,您应该考虑 Pyrolistical 链接。