0

How can I remove a JScrollPane from a JFrame?

Here is an example of what I tried, but it isn't working:

Container gContentPane = frame.getContentPane();
JScrollPane scroll = new JScrollPane(gContentPane);
frame.setContentPane( scroll );
frame.revalidate();
frame.repaint();

if (scroll != null){
    frame.getContentPane().remove(scroll);                      
    frame.revalidate(); 
    frame.repaint();
}

The JScrollPane is still there even after frame.getContentPane().remove(scroll);. What do I need to change to remove it?

nhouser9
  • 6,730
  • 3
  • 21
  • 42
user2129896
  • 307
  • 1
  • 7
  • 26
  • 1
    You really should change frame.setContentPane(scroll) to `frame.getContentPane().add(scroll)`. Currently, your code is trying to remove the JScrollPane from itself. – VGR Sep 26 '16 at 17:30
  • Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Sep 27 '16 at 01:26

1 Answers1

2

If you want to remove something in Swing, firstly it has to be added. You did not add the scroll pane nowhere so I would suggest just changing the content pane to the previous one.

Container gContentPane = frame.getContentPane();
JScrollPane scroll = new JScrollPane(gContentPane);
frame.setContentPane( scroll );
frame.revalidate();
frame.repaint();

if (scroll != null) {
    frame.setContentPane(gContentPane);
    frame.revalidate();
    frame.repaint();
}
Wojtek
  • 1,288
  • 11
  • 16