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"}));
            JButton button = new JButton("Show Table");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {        

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…


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

panel.revalidate(); // to invoke the layout manager
panel.repaint();  // sometimes needed to make sure panel is repainted

Source: stackoverflow