Search code examples
javaswingnetbeansjframenetbeans-8

How to remove JscrollPane from JFrame?


I have problems with removing JScrollPanels from jFrame.

This is code for adding JScrollPanel after click:

jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {

                if(count_games == 0)
                    {
                        Game game = new Game();
                        game.setPreferredSize(new Dimension(1000,1000));
                        game1 = new JScrollPane(game);
                        frame.add(game1);

                        game1.setBounds(0, 40, 1000, 960);


                        count_games ++;
                    }else if(count_games == 1)...

and this is code for removing JScrollPanel:

jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    if(count_games == 1)
                    {


                        game1.removeAll();
                        game1.revalidate();
                        game1.repaint();

                        count_games --;

                    }else if(count_games == 2)...

After remove empty wireframe stays in JFrame. Example: Before remove

After remove


Solution

  • game1.removeAll();
    

    This removes all components added to the JScrollPanel. If you want to remove this whole panel, You need to remove it from the JFrame.

    So replace this statement with:

    frame.remove(game1);
    

    Or If you want to make your frame empty call frame.removeAll(); method.