-2

In my Frame i have have a title screen(J Panel) and when i click a button i want it to be replaced with the game screen(another J Panel). i have this code to replace it, but when i click the button to send it to my start method it clears the GUI and it just stays blank.

public void start() {
         frame.remove(titlePanel);
         frame.repaint();
         frame.add(gamePanel);
}

if i add the gamePanel to the frame where i did the titlePanel it works fine so i know it is finding the image.

any help would be much appreciated.

3 Answers3

1

A preferred solution would be to use CardLayout, which will allow you to switch out views easily...

The direct approach (which you are doing now) should be fixed by calling frame.revalidate() after you've added the gamePanel...but I'd still recommend the CardLayout

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You have to use frame.revalidate() to get changes working.

Baalthasarr
  • 377
  • 1
  • 13
0

Try this:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
public class test extends JFrame {
    private JPanel contentPane;
    JPanel panel1;
    JPanel panel2;
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    test frame = new test();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        panel1 = new JPanel();
        contentPane.add(panel1, BorderLayout.NORTH);
        panel1.setBackground(Color.red);

         panel2 = new JPanel();
         panel2.setBackground(Color.blue);

        JButton btnNewButton = new JButton("New button");
        contentPane.add(btnNewButton, BorderLayout.SOUTH);
        btnNewButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                remove(panel1);
                contentPane.add(panel2, BorderLayout.NORTH);
                repaint();
                validate();
            }
        });
    }

}
Arijit
  • 1,633
  • 2
  • 21
  • 35