How to display a JTable in a JPanel with Java?

前端 未结 2 2037
野性不改
野性不改 2020-12-17 01:50

How to display a JTable in a JPanel with Java?

2条回答
  •  北海茫月
    2020-12-17 02: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.

提交回复
热议问题