newbie
newbie

Reputation: 14950

JPanel Problem in Java

Good day!

I have a problem in reseting the contents of my JPANEL. Is there a method in deleting all the contents of the JPANEL?

I am making a HangMan Game. And i need to initialize my panel to give way to the next level. My panel is created using Netbeans GUI and everything is fixed (even the position and size).

My SAMPLE code is as follows:

 public MainGame(JDialog owner) {
        super(owner, true);
        initComponents();
        newGame();
    }

    void newGame() {
         jPanel3.setLayout(new GridLayout(3, 9, 3, 5));
         for (char buttonChar = 'a'; buttonChar <= 'z'; buttonChar++) {
             String buttonText = String.valueOf(buttonChar);
             letterButton = new JButton(buttonText);
             letterButton.addActionListener(this);
             jPanel3.add(letterButton);
         }
    }

    void checkHame(){
         newGame();   //I CALL AGAIN TO GO TO THE NEXT LEVEL...
    }

In my code, jPanel3 is created by using the GUI of netbeans. My problem is, on the first call of newGame method, the JPanel3 is filled with contents.. I need to delete all the contents inside for my second newGame call or else all the contents will ADD UP or double up.

Any suggestions will be highly appreciated.

Thank you once again!

Cheers.

Upvotes: 0

Views: 403

Answers (3)

limc
limc

Reputation: 40160

How about doing a jPanel3.removeAll() before the for loop?

Definition for removeAll():-

public void removeAll()

Removes all the components from this container.

Upvotes: 2

Bogdan
Bogdan

Reputation: 5406

Also you may need to call revalidate() & repaint() after removeAll

Upvotes: 2

Jeff Storey
Jeff Storey

Reputation: 57182

You can use the removeAll method.

Rather than removing the components though, you might just consider resetting the state of the buttons back to their original and just reusing the buttons.

Upvotes: 1

Related Questions