Why can't I view my JLabel added to JPanel while using graphics?

I am trying to add a JLabel under the boards that is painted with graphics. I set the x and y position of JLabel somewhere under the board

    pName = new JLabel("Yoooooo");
    pName.setBounds(180,500,50,50);
    this.add(pName);

However I can't view it when I run the code. What can be the reason?

Edit: Now I can view it thx to Andrew but I can't locate it to the position that I want.

JLabel should be under the board.

pName.setBounds(180,500,50,50); 

seems not working. Why can it be?

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);

            }
        }
      }


 }

Here is the output:

Answers


Once you override paint(Graphics g) you are on your own on painting the component. This means that no matter what other stuff you do outside paint, it may not count much as the real paint happens in your custom implementation and not in the default JPanel one.


Need Your Help

Autodetect classes in Hibernate from jar

java hibernate java-ee jboss

I have a JavaEE project with several entities with the following persistence.xml file:

Generate a CIL executable not EXE then execute it

c# .net cil

I have a c# project that generates an EXE file. Now, I'm in a "secure" corporate environment, where I can compile my project, but I cannot execute the EXE file.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.