user2680383
user2680383

Reputation: 5

Java changing the content of JFrame problems

I'm trying to change the content of the Jframe so it is from the menu screen to the game itself. It is like you click the start game then you will be able to play the game. So far I have successfully changed the contents but the controls of the game aren't able to be detected from my code. For example, I press Space so the character from the game will shoot but whenever I press it I cannot notice anything happening. I've seen the topics that are quite similar to this but those haven't helped me solve my issue. So, here's my code:

package rtype;

import javax.swing.JButton;
import javax.swing.JFrame;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Rtype extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public Rtype() {
    setSize(1020, 440);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setTitle("PROJECT JAEGER");
    setResizable(false);
    setVisible(true);
    JButton startButton = new JButton("START GAME");//The JButton name.
    add(startButton);//Add the button to the JFrame.
    startButton.addActionListener(this);//Reads the action.
}

public static void main(String[] args) {
    new Rtype();
}
public void actionPerformed(ActionEvent i) {
    getContentPane().removeAll();
    add(new Board());
    setVisible(true);  
        System.out.println("The Button Works!");//what the button says when clicked.
    }
}

Calling add(new Board()); summons the game. The Board is the class of the game.

Upvotes: 0

Views: 75

Answers (1)

tbodt
tbodt

Reputation: 16987

The solution is very simple. After changing what is in the frame, you need to invoke revalidate to make the changes take effect. Just add this line of code to the end of actionPerformed and it will work:

revalidate();

Upvotes: 1

Related Questions