as the title says, I would like to add a JLabel to a class (in my case, named GamePanel) which extends JPanel. I tried with
public class GamePanel extends JPanel implements Runnable, KeyListener
{
/*Some of my instructions
*
*/
public void gamelabel()
{
JLabel mylabel = new JLabel();
mylabel.setBounds(0, 0, 1280, 720);
GamePanel.add(mylabel); //Here I'm getting an error message
}
/*Others instructions
*
*/
}
So I really don't know how to do it, but I have the feeling it must be an easy solution... Nevertheless, I couldn't find it.
How could I do it? Thanks in advance.
use this.add()
instead of Gamelabel.add()
.
you can't call Gamelabel.add()
because to call Gamelabel.add()
there should be a static method add()
in Gamelabel
class but Gamelabel has a inherited instance method add()
not a static method .
public void Gamelabel() {
JLabel mylabel = new JLabel();
mylabel.setBounds(0, 0, 1280, 720);
mylabel.setVisible(true); //unnecessary
this.add(mylabel);
}
also use layout managers .in your code you can't use setBounds()
method because panel layout is flow (default) . setbounds
is used for absolute positioning when not using layout managers. so read how to use layout managers and flow layout .
also mylabel.setVisible(true);
is unnecessary because jlable
is visible by default unlike jframe
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.