我正在尝试在涂有图形的板下添加一个JLabel。我将JLabel的x和y位置设置在董事会的某个位置
pName = new JLabel("Yoooooo");
pName.setBounds(180,500,50,50);
this.add(pName);
但是,当我运行代码时,我无法查看它。可能是什么原因?
编辑:现在我可以将它视为安德鲁,但我找不到它想要的位置。
JLabel应该在董事会之下。
pName.setBounds(180,500,50,50);
似乎不起作用。为什么会这样?
public class EnemyPanel extends JPanel{
private char enemyBoard[][] = new char[10][10]; //to keep state of squares
private Rectangle r[][] = new Rectangle[10][10];//to give coordinates and boundaries to squares
private int size;
private JLabel pName;
public EnemyPanel()
{
size=Constant.rectSize;
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
enemyBoard[i][j]='*'; //initialization type
r[i][j]= new Rectangle(j*size+30,i*size+30, size, size);
}
}
pName = new JLabel("Yoooooo");
pName.setBounds(180,500,50,50);
this.add(pName);
}
public void paint(Graphics g){
super.paintComponent(g);
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
if(enemyBoard[i][j]=='!'){
//hit square's color is changed to white
g.setColor(Color.white);
}
else if(enemyBoard[i][j]=='$')
//miss square's color is changed to gray
g.setColor(Color.gray);
else
//undiscovered ones are green
g.setColor(Color.green);
g.fill3DRect((int)r[i][j].getX() ,(int)r[i][j].getY(),(int)r[i][j].getWidth(), (int)r[i][j].getHeight(), true);
}
}
}
}
这是输出:
答案 0 :(得分:1)
覆盖paint(Graphics g)
后,您可以自行绘制组件。这意味着无论你在paint
之外做了什么其他的事情,它都可能不像真正的油漆在你的自定义实现中发生,而不是默认的JPanel
。
答案 1 :(得分:0)
我的第一个问题是我无法查看JLabel组件。 根据安德鲁的评论,我解决了这个问题。 如果您在面板中使用其他组件,则应使用paintComponent而不是paint。
其次,我无法查看我想要的JLabel。因此,为了将特定位置设置为JLabel,应将JPanel布局设置为null。 this.setLayout(null)解决了我的第二个问题。