Adding a JScrollPane to a JTable Component

I am trying to add a JScrollPane to my JTable , but it does not work. I have a JTable with 21 JTable and 5 columns, and I add JScrollPane according to 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); } 

Can someone please help me understand why scrollbars do not appear.

+4
source share
2 answers

Make sure you add the JScrollPane to the JFrame and not to the JTable . If you originally just had JFrame and JTable , you would add it like this ...

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

If you add JScrollPane , you need to change your add() method to add JScrollPane instead of JTable , like this ...

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

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

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

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

-1
source

Source: https://habr.com/ru/post/1412783/


All Articles