Adding a JScrollPane to a JTable component

拥有回忆 提交于 2019-12-17 20:50:36

问题


I am trying to add a JScrollPane to my JTable, but it doesn't seem to works. I have a JTable with 21 rows and 5 columns, and I'm adding a JScrollPane as per the following code...

public Targy_felv() {
    JScrollPane scrollPane;
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(600, 300);
    table = new JTable();
    Object o[] = new Object[]{"Tárgynév", "Oktató", "Kredit", "Félév", "Tárgykód"};
    table.setModel(new DefaultTableModel(get_Tárgyak(), o));
    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(table);
    frame.add(table);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Could someone please help me to understand why the scrollbars aren't appearing.


回答1:


Make sure you're adding the JScrollPane to your JFrame, not the JTable. If you originally just had a JFrame and a JTable you would have added it like this...

JTable table = new JTable();
JFrame frame = new JFrame();
frame.add(table);

If you're adding the JScrollPane, you need to change your add() method to add the JScrollPane instead of the JTable, either like this...

JTable table = new JTable();
JFrame frame = new JFrame();
frame.add(new JScrollPane(table));

or like this, if you need to reference the JScrollPane later in your code...

JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame();
frame.add(scrollPane);



回答2:


I noticed in the initial code frame.add(table); change 'table' to 'scrollPane' and it works.



来源:https://stackoverflow.com/questions/10619048/adding-a-jscrollpane-to-a-jtable-component

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