且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 08:25:22

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

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.