So I am pretty new to java and programming (4 months) and I am trying to make a basic snake game with a menu. I am switching between each different component by adding and removing them on the frame. Here is the code:
public class screen extends Frame {
private static final long serialVersionUID = 1L;
private static screen f;
private static menu ex;
private static loadsettings settings;
public screen(String frameLabel, int width, int height) {
setSize(width, height);
setLocation(50,50);
setResizable(true);
setUndecorated(true);
setVisible(true);
}
public static void main(String[] args){
settings = new loadsettings();
f = new screen("Game", settings.getWindowWidth(), settings.getWindowHeight());
ex = new menu(f,settings);
f.add(ex);
ex.createBufferStrategy(2);
ex.requestFocus();
}
public static void new1Player(){
f.setSize(400,400);
f.removeAll();
player1 ex = new player1(f,settings);
f.add(ex);
ex.createBufferStrategy(2);
ex.requestFocus();
}
public static void new2Player(){
f.setSize(600,600);
f.removeAll();
player2 ex = new player2(f,settings);
f.add(ex);
ex.createBufferStrategy(2);
ex.requestFocus();
}
public static void newMenu(){
f.setSize(400,400);
f.removeAll();
menu ex = new menu(f,settings);
f.add(ex);
ex.createBufferStrategy(2);
ex.requestFocus();
}
}
The thing is, each component is a Canvas, so they are constantly being added and removed. I just want to know, is this bad coding and is there a better way to do this?
Thanks.
Read about using the CardLayout.
You can use a Canvas if you like, but theres no reason you couldn’t just use Panels.