gpt4 book ai didi

java - 在程序中使用多个 Canvas (不同时)是错误/不好的吗?

转载 作者:行者123 更新时间:2023-11-29 09:16:51 25 4
gpt4 key购买 nike

所以我对 Java 和编程(4 个月)还很陌生,我正在尝试制作一个带有菜单的基本贪吃蛇游戏。我通过在框架上添加和删除它们来在每个不同的组件之间切换。这是代码:

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();
}
}

问题是,每个组件都是一个 Canvas,因此它们会不断地被添加和删除。我只是想知道,这是糟糕的编码吗?有没有更好的方法来做到这一点?谢谢。

最佳答案

阅读有关使用 CardLayout 的信息.

A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.

您可以根据需要使用 Canvas,但没有理由不能只使用 Panel。

关于java - 在程序中使用多个 Canvas (不同时)是错误/不好的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8872615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com