Java 有没有一种有效的方法可以在我的游戏中持续创建更多的矩形?
我正在尝试制作一个名为“jump it”()的java GUI游戏版本。我目前正在绘制随机矩形,以便我的角色可以在上面跳跃。然而,我不知道如何不断地绘制更多的矩形,因为我对GUI还相当陌生。下面是我的代码,希望你们能帮助我Java 有没有一种有效的方法可以在我的游戏中持续创建更多的矩形?,java,user-interface,drawrectangle,Java,User Interface,Drawrectangle,我正在尝试制作一个名为“jump it”()的java GUI游戏版本。我目前正在绘制随机矩形,以便我的角色可以在上面跳跃。然而,我不知道如何不断地绘制更多的矩形,因为我对GUI还相当陌生。下面是我的代码,希望你们能帮助我 class BtnActPanel extends JPanel implements ActionListener{ private int x = 0, x1 = 650, y2 = (int)(Math.random()*100)+40, y1 = (in
class BtnActPanel extends JPanel implements
ActionListener{
private int x = 0,
x1 = 650,
y2 = (int)(Math.random()*100)+40,
y1 = (int)(Math.random()*100)+450,
x2 = (int)(Math.random()*600)+200;
.
.
.
}
public void actionPerformed(ActionEvent e) {
.
.
.
else if (e.getSource() == b3){
JOptionPane.showMessageDialog(null, "This is an exit button, hope you enjoyed the game! :)", "Exit message",JOptionPane.WARNING_MESSAGE ); //shows exit message
System.exit(0);//exits program
}
else if (e.getSource() == t){
if (index == 0){
index = 1;
c = arrImage[1];
}
else{
index = 0;
c = arrImage[0];
}
x = x-10;
x1 = x1-10;
repaint();
}
}
public void paintComponent(Graphics g){//this method draws and paints images and icons based on the user decisions
super.paintComponent(g);
if(check1 == 0)
g.drawImage(icon.getImage(),0,0,null);
if(check1 == 1){
g.drawImage(b.getImage(),0,0,null);
g.setColor(Color.black);
g.fillRect(x,495, 500, 35);
g.fillRect(x1, y1, x2, y2);
g.drawImage(c.getImage(), 100, 460, null);
}
if(check1 == 2)
g.drawImage(instruct.getImage(),0,0,null);
b1.setBounds(320, 350, 100, 100);
b2.setBounds(420, 350, 100, 100);
b3.setBounds(520, 350, 100, 100);
}
}//课后您可以设置计时器或在循环中生成一些计时器 您可以根据需要调整阈值
static Random r = new Random();
static int upperX = 100;
static int lowerX = 20;
static int upperY = 100;
static int lowerY = 50;
static int minWidth = 100;
static int maxWidth = 300;
static int minHeight = 50;
static int maxHeight = 200;
public static Rectangle newRect() {
// All ranges inclusive of thresholds
int x = r.nextInt(upperX-lowerX + 1) + lowerX; // from 20 to 100
int y = r.nextInt(upperY-lowerY + 1) + lowerY; // from 50 to 100
int w = r.nextInt(maxWidth-minWidth + 1) + minWidth; // from 100 to 300
int h = r.nextInt(maxHeight - minHeight + 1) + minHeight; // from 50 to 200
return new Rectangle(x,y,w,h);
}
在大多数游戏中,你会有一个“主循环”。此循环检查当前输入,修改游戏的各种状态,并安排绘制过程。根据您使用的底层框架,这将以不同的方式实现。例如,在Swing中,您可以使用Swing
计时器
,因为它在事件调度线程的上下文中滴答作响,使一般使用更容易、更安全。您可能需要考虑的另一个问题是创建短期对象。短暂的对象可能会给系统带来压力,因为GC机制需要花费更多的时间来查找和收集这些对象,而对象创建本身就有一个问题。更好的办法可能是“汇集”对象并重用它们,根据需要修改参数(位置和大小)。这是一个更复杂的想法,但将有助于保持平稳的体验-这里有两个使用swingTimer
随机生成短期形状的示例:和