Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a JScrollPane to a JTable component

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.

like image 292
Tamás Nyiri Avatar asked Dec 17 '22 00:12

Tamás Nyiri


1 Answers

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);
like image 118
wattostudios Avatar answered Mar 04 '23 17:03

wattostudios