0

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...

  • 1
    Ask your question with the question, not in the comments. Post a proper [mre] demonstrating the problem. We can't tell if you actually add the scrollpane to the frame. You may also need to revalidate() and repaint() the panel. – camickr Jun 01 '21 at 17:47
  • @camickr sorry i am new to this platform didnt knew. but yeah revaildate() and repaint() worked for me. thanks. could you write it in answer so that i can accept it as correct answer – The Warrior Jun 01 '21 at 17:53

1 Answers1

0

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
camickr
  • 321,443
  • 19
  • 166
  • 288