【发布时间】:2011-07-11 22:24:45
【问题描述】:
我有一个扩展 JPanel 的类,我想在它上面添加一些标签(实际上是一个扩展 JLabel 的类)。此面板的布局为 null。我已经设置了标签的大小和位置,但问题是我无法在正确的位置看到它:( 我在控制台中打印了 getComponentAt(....).getClass().getName() 以查看该位置中真正存在的内容并得到了正确答案(我的意思是 getComponent 说在我添加它的地方有一个标签,但问题是我在位置(0,0)看到我的标签,这是错误的):-S 我在我的代码中找不到任何错误:-/ 任何帮助表示赞赏,在此先感谢。 :) 这是我的代码的相关部分:
public class ServerViewManager extends JPanel implements Serializable {
private ArrayList<String> map;
// *tankview extends JLabel
private ArrayList<TankView> tanks = new ArrayList<TankView>();
private ArrayList<BulletView> bullets = new ArrayList<BulletView>();
private int rows;
private int columns;
public ServerViewManager(ArrayList<String> map) {
super(null);
this.map = map;
rows = map.size();
columns = map.get(0).length();
for (int i = 0; i < map.size(); i++) {
for (int j = 0; j < map.get(i).length(); j++) {
if (map.get(i).charAt(j) == 'i')
add(new IceBlock(i, j));
else if (map.get(i).charAt(j) != 'g')
add(new Block(map.get(i).charAt(j), i * 50, j * 50));
}
}
}
public void paintComponent(Graphics g) {
g.drawImage(Resources.GROUNDBLOCK.getImage(), 0, 0, columns * 50,
rows * 50, this);
}
//************************************************
// Here is where i wanna put the label
public void addTank(Color color, int xpos, int ypos) {
tanks.add(new TankView(color, xpos, ypos));
if (iceBlock(xpos, ypos)) {
IceBlock ice = (IceBlock) this.getComponentAt(ypos * 50, xpos * 50);
ice.putItem(color + "1");
} else
this.add(tanks.get(tanks.size() - 1));
repaint();
}
这是我的标签:
public class TankView extends JLabel implements Serializable{
private int xpos;
private int ypos;
private char direction;
private int directionNum;
private Color color;
public TankView(Color color, int x, int y) {
xpos=x;
ypos=y;
direction='u';
directionNum=1;
setLocation(ypos *50, xpos*50);
setSize(50, 50);
setOpaque(false);
setVisible(true);
this.color=color;
if (color==Color.Blue)
setIcon(Resources.BlueTank1);
else if (color==Color.Green)
setIcon(Resources.GreenTank1);
else if (color==Color.Red)
setIcon(Resources.OrangeTank1);
else if (color==Color.Yellow)
setIcon(Resources.PinkTank1);
repaint();
}
【问题讨论】:
-
我们看不到您在哪里调用了
addTank方法。你能展示一下吗? -
如需尽快获得更好的帮助,请发帖SSCCE。