How to display a JTable in a JPanel with Java?

半城伤御伤魂 提交于 2019-11-29 04:34:31

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.

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..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!