所以我试图制作一个简单的PacMan克隆,我已经到了添加图像等的阶段。我有两个图像(到目前为止),它们是:
和,trackball.png和border.png
所以我用new oicMan();
运行下面的代码,这就是我得到的:
控制台输出:
.
.
.
Placing image border on coordinate (225,250)
Placing image border on coordinate (225,275)
Placing image border on coordinate (225,300)
Placing image border on coordinate (225,325)
Placing image border on coordinate (225,350)
Placing image border on coordinate (225,375)
Placing image border on coordinate (225,400)
Placing image border on coordinate (225,425)
Placing image border on coordinate (225,450)
Placing image border on coordinate (225,475)
所以它似乎停在x = 225。谁能告诉我为什么?我的for
循环设置图像是一个问题吗?谢谢(主要是请告诉我为什么它没有完全绘画。)
import javax.swing.*;
import java.awt.*;
public class oicMan extends JFrame
{
Container container;
/*
####################
# ## #
# ## ############# #
# ## ############# #
# ## # #
# ## # ##### ##### #
# ## ##### ##### #
# ## # ##### ##### #
# # #
####################
*/
String arena[][] =
{
{"#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#"},
{"#"," ","#","#"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ","#"},
{"#"," ","#","#"," ","#","#","#","#","#","#","#","#","#","#","#","#","#"," ","#"},
{"#"," ","#","#"," ","#","#","#","#","#","#","#","#","#","#","#","#","#"," ","#"},
{"#"," ","#","#"," ","#"," "," "," "," "," "," "," "," "," "," "," "," "," ","#"},
{"#"," ","#","#"," ","#"," ","#","#","#","#","#"," ","#","#","#","#","#"," ","#"},
{"#"," ","#","#"," "," "," ","#","#","#","#","#"," ","#","#","#","#","#"," ","#"},
{"#"," ","#","#"," ","#"," ","#","#","#","#","#"," ","#","#","#","#","#"," ","#"},
{"#"," "," "," "," ","#"," "," "," "," "," "," "," "," "," "," "," "," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#"},
};
public oicMan()
{
super("oicMan");
setSize(500, 250);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = getContentPane();
container.setLayout(null);
container.setBackground(Color.black);
for(int i = 0; i < arena.length; i++)
{
for(int j = 0; j < arena[0].length; j++)
{
JLabel label = null;
if(arena[ i][ j].equals("#"))
{
label = new JLabel(new ImageIcon("border.png"));
label.setName("border");
}
else
{
label = new JLabel(new ImageIcon("trackball.png"));
label.setName("track");
}
container.add(label);
label.setBounds(i*25,j*25,25,25);
System.out.println("Placing image "+label.getName()+" on coordinate ("+i*25+","+j*25+")");
}
}
repaint();
container.validate();
setContentPane(container);
}
}
答案 0 :(得分:0)
当你调用label.setBounds(i * 25,j * 25,25,25)时,似乎你可能已经颠倒了行和列。我想将这行代码更改为label.setBounds(j * 25,i * 25,25,25);应该解决问题。 JLabel setBounds方法的参数如下:JLabel:setBounds(int x,int y,int width,int height)
这意味着当您认为自己正在设置JLabel的y值时,您实际上是在设置x值,反之亦然。
一条好的建议是始终阅读您可能正在使用的任何库的文档。
但是,我总是很乐意提供帮助。干杯,希望这有助于解决您的问题!
答案 1 :(得分:0)
问题在于您的arena[][]
。它有10 rows
和20 columns
,这实际上意味着您的for
循环只会针对200
块运行。
要覆盖整个屏幕,您需要相应地调整arena[][]
。
P.S: (225,475)
是因为(i*25+","+j*25)
其中i=9
为最高,j=19
为最高。