Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to clear a JFrame in java swing?

I’m trying to make that once the button play is pressed the method startingGame in the class GameUI will be called and that method will delete everything inside the actual frame, to leave it completely blank so that I can continue building a new one.
My aim is creating a connect 4 game therefore the first frame created under the class UI, will be the starting page, while once the button play is pressed, a new frame with the game will appear, under the same window.

    import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class UI {
    JFrame frame = new JFrame();
    JButton play = new JButton("Play");
    JLabel inputUsername = new JLabel("Username", JLabel.RIGHT);
    JTextField username = new JTextField(13);
    private String Player1;

    public UI() {

        //Load the background Image.
        ImageIcon imgBackground = new ImageIcon(this.getClass().getResource("/img/connect4_4.png"));

        //Create the frame.
        JFrame frame = new JFrame("Connect 4");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Setting a JLabel which contains an image to the content pane of the frame,
        //So that the image is displayed as a background.
        frame.setContentPane(new JLabel((imgBackground)));

        //Any components added to the frame will be arranged according to GridBadLayout manager.
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        //sets padding botton to 20 within the elements of the grid.
        gbc.insets = new Insets(0, 0, 20, 0);
        //make the play Button bigger.
        play.setPreferredSize(new Dimension(200, 75));
        //Add it to the frame.
        play.setFont(new Font("Britannic Bold", Font.PLAIN, 30));
        Color myColor = Color.decode("#CDCDCD");
        play.setBackground(myColor);
        
        play.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Retrieve the text from the JTextField and save it to the variable
                Player1 = username.getText();
                System.out.println("Username entered: " + Player1);
                GameUI startGame = new GameUI();
                startGame.startingGame();
            }
        });

        frame.add(play, gbc);
        //readjusts the padding of the elemts inside the grid.
        gbc.insets = new Insets(0, 0, 2, 0);
        inputUsername.setFont(new Font("Britannic Bold", Font.PLAIN, 20));
        frame.add(username, gbc);
        username.setFont(new Font("Corbel", Font.PLAIN, 15));
        username.setHorizontalAlignment(JTextField.CENTER);
        frame.add(inputUsername, gbc);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

 
}

class GameUI extends UI {

    public void startingGame() {

        frame.getContentPane().removeAll();
        frame.setVisible(true);

    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In your code, the startingGame method in the GameUI class attempts to clear the frame from the UI class. However, there is a scoping issue with the JFrame frame that prevents it from behaving as you expect.

In the constructor of the UI class, you declared a local variable JFrame frame, which shadows the class member JFrame frame.

Here’s the line causing the problem:

JFrame frame = new JFrame("Connect 4");

Change it to:

frame = new JFrame("Connect 4");

This way, you are initializing the class member frame, rather than creating a local variable, and the GameUI class should then be able to access and manipulate the same frame.

Here’s the corrected version of your UI class:

public class UI {
    JFrame frame = new JFrame();
    JButton play = new JButton("Play");
    JLabel inputUsername = new JLabel("Username", JLabel.RIGHT);
    JTextField username = new JTextField(13);
    private String Player1;

    public UI() {
        // ... (no change here)

        frame = new JFrame("Connect 4"); // Notice the change here
        // ... (rest of the code remains same)
    }
    // ...
}

And your GameUI class, which looks fine:

class GameUI extends UI {
    public void startingGame() {
        frame.getContentPane().removeAll();
        frame.setVisible(true);
    }
}

Now, when you call startingGame() it should work as expected by removing all components from frame and making it visible again. You can then proceed to add new components for your Connect 4 game.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading