Skip to content
Advertisement

JTable not visible inside JScrollPane

I have a JTable inside a JScrollPane. I want to show the table only when a particular button is pressed otherwise it should not be shown.

Inorder to incorporate that I have set the setVisible method of the ScrollPane to false while declaring and I set it to true inside the actionPerformed method of the JButton.

But the JTable is not visible even when I press the JButton.

Here’s my code:

     public class TableSample{
        private JTable table;
     ....
        private void initialize() {
            JScrollPane scrollPane = new JScrollPane();
            table = new JTable(new DefaultTableModel(new Object[][] {{null, null}, {null, null}, }, new String[] {"column1", "column2"}));
            scrollPane.setViewportView(table);
            scrollPane.setVisible(false);
            JButton button = new JButton("Show Table");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {        
                     ....
                     scrollPane.setVisible(true);
                     ....
                }
            });
     ....
        }

I have used group layout so the ScrollPane is added to frame with group layout.

Also the JTable is visible when I do not change the setVisible at all (by default true)

Any help is appreciated…

Advertisement

Answer

When you add components to a visible GUI the basic logic is:

panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint();  // sometimes needed to make sure panel is repainted
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement