[英]How to add a JLabel to a class which extends JPanel
as the title says, I would like to add a JLabel to a class (in my case, named GamePanel) which extends JPanel.正如标题所说,我想将一个 JLabel 添加到一个扩展 JPanel 的类(在我的例子中,名为 GamePanel)。 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()
.使用
this.add()
而不是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 .你不能调用
Gamelabel.add()
因为要调用Gamelabel.add()
应该在Gamelabel
类中有一个静态方法add()
但 Gamelabel 有一个继承的实例方法add()
而不是静态方法。
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()
方法,因为面板布局是 flow (default) 。 setbounds
is used for absolute positioning when not using layout managers. setbounds
用于不使用布局管理器时的绝对定位。 so read how to use layout managers and flow layout .所以阅读如何使用布局管理器和流布局。
also mylabel.setVisible(true);
还有
mylabel.setVisible(true);
is unnecessary because jlable
is visible by default unlike jframe
.是不必要的,因为
jlable
与jframe
不同,默认情况下是可见的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.