How to completely get rid of a JPanel
and everything in it while running?
package textgame;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class EscapeFromPrison extends JFrame implements ActionListener{
JButton startGameButton;
JButton creditsButton;
JButton choice1;
Button choice2;
JLabel mainTitleLabel;
JLabel question;
JLabel space;
JLabel credits;
JPanel titleScreen;
public EscapeFromPrison(){
super("Escape From Prison");
setLookAndFeel();
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainTitleLabel = new JLabel("<html>Escape From Prison</html>");
startGameButton = new JButton("<html>START<html>");
startGameButton.setActionCommand("StartGameButton");
creditsButton = new JButton("<html>CREDITS</html>");
creditsButton.addActionListener(this);
creditsButton.setActionCommand("CreditsButton");
question = new JLabel("");
space = new JLabel("");
credits = new JLabel("");
choice1 = new JButton("");
choice2 = new JButton("");
JPanel titleScreen = new JPanel();
BoxLayout titleScreenLayout = new BoxLayout(titleScreen, BoxLayout.Y_AXIS);
titleScreen.setLayout(titleScreenLayout);
titleScreen.add(mainTitleLabel);
titleScreen.add(startGameButton);
titleScreen.add(creditsButton);
add(titleScreen);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent buttonClick){
String event = buttonClick.getActionCommand();
In this if statement I want to get rid of mainTitleLabel
, startGameButton
, and creditsButton
. So question can be in the top left position, cause right now they are currently invisible and the question is in the top right position. I am using grid layout.
if(event.equals("StartGameButton")){
GridLayout grid = new GridLayout(2,2);
setLayout(grid);
question.setText("<html>text</html>");
choice1.setActionCommand("");
choice1.setText("");
choice2.setActionCommand("");
choice2.setText("");
mainTitleLabel.setVisible(false);
startGameButton.setVisible(false);
creditsButton.setVisible(false);
add(question);
add(choice1);
add(choice2);
setVisible(true);
}
if(event.equals("CreditsButton")){
FlowLayout flo = new FlowLayout();
setLayout(flo);
credits.setText("<html></html>");
mainTitleLabel.setVisible(false);
startGameButton.setVisible(false);
creditsButton.setVisible(false);
add(credits);
setVisible(true);
}
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
}catch(Exception exc){
//ignore error
}
}
public static void main(String[] arguments){
EscapeFromPrison frame = new EscapeFromPrison();
}
}