user5741208
user5741208

Reputation:

Adding Jbuttons and Jlabel

So my code already makes a starting menu made of buttons and a label. When one of the buttons is pressed I want to remove everything (Which it does) and show a new label and a button. Only the new items do not appear, please help

public void HighScoreScreen(String HighScores){
    //first we need to get rid of what's already there (this works)
    remove(title);
    remove(newGameButton);
    remove(twoPlayerButton);
    remove(highScore);

    //now adding what I want to show (doesn't work)
    highScoreSheet = new JLabel(HighScores);
    gbc.gridx = 0;
    gbc.gridy = 0;
    add(highScoreSheet, gbc);

    menu = new JButton("Menu");
    gbc.gridx = 0;
    gbc.gridx = 1;
    add(menu, gbc);
    repaint();
}

I think that's all that's relevant but if you need the code where I first make the menu here it is:

   public GUI(){
    super("Snake Game");

    setLayout(new GridBagLayout());

    gbc.insets = new Insets(20, 20, 0, 0); 

    title = new JLabel("SNAKE");
    gbc.gridx = 0;
    gbc.gridy = 0;
    add(title, gbc);

    newGameButton = new JButton("New Game");
    gbc.gridx = 0;
    gbc.gridy = 1;
    add(newGameButton, gbc);

    twoPlayerButton = new JButton("2 player Mode");
    gbc.gridx = 0;
    gbc.gridy = 2;       
    add(twoPlayerButton, gbc);

    highScore = new JButton("HighScores");
    gbc.gridx = 0;
    gbc.gridy = 3;        
    add(highScore, gbc);

    ButtonHandler handler = new ButtonHandler();

    newGameButton.addActionListener(handler);
    twoPlayerButton.addActionListener(handler);
    highScore.addActionListener(handler);

}

The action lister this code refers to is in a class within this class and works fine, when highscore is pressed it will do its thing then call the first code block I showed.

And finally here is the main, just in case you need it:

public class SnakeGame extends Canvas implements Runnable {

public boolean read = false; 

public SnakeGame(){

    GUI frame = new GUI();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,300);
    frame.setVisible(true);
}

public void run(){

}
public static void main(String[] args) {
    SnakeGame Game = new SnakeGame(); 

 }
}

Upvotes: 0

Views: 472

Answers (1)

camickr
camickr

Reputation: 324098

Don't mix AWT components in a Swing Application. Canvas is AWT. Use a JPanel for custom painting.

The basic code when adding/removing components on a visible GUI is:

panel.remove(...);
panel.add(...);
panel.revalidate(); // to invoke the layout manager
panel.repaint();

If you don't invoke the layout manager then the components have a 0 size so there is nothing to paint.

Upvotes: 3

Related Questions