【发布时间】:2019-12-31 20:13:56
【问题描述】:
我正在尝试制作名为“jump it”(http://www.crazygames.com/game/jump-it) 的游戏的 java GUI 游戏版本。我目前正在为我的角色绘制随机矩形以供跳跃。但是,我不知道如何连续绘制更多矩形,因为我对 GUI 还很陌生。所以我的代码在下面,我希望你们能帮助我!
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);
}
}//课程结束
【问题讨论】:
-
在大多数游戏中,您都会有一个“主循环”。该循环检查当前输入,修改游戏的各种状态并安排一次绘画通道。根据您使用的底层框架,这将以不同的方式实现。例如,在 Swing 中,您可以使用 Swing
Timer,因为它在 Event Dispatching Thread 的上下文中滴答作响,使其更容易和更安全地使用 -
您可能需要考虑的另一个考虑因素是创建短期对象。短期对象会给系统带来压力,因为 GC 机制需要花费更多时间来寻找和收集这些对象,并且对象创建本身有开销。更好的想法可能是“汇集”对象并重新使用它们,根据需要修改参数(位置和大小)。这是一个更复杂的想法,但有助于保持流畅的体验 - for example
标签: java user-interface drawrectangle