如何将 JLabel 添加到扩展 JPanel 的 class
How to add a JLabel to a class which extends JPanel
如标题所述,我想将 JLabel 添加到扩展 JPanel 的 class(在我的例子中,命名为 GamePanel)。我试过
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
*
*/
}
所以我真的不知道该怎么做,但我觉得这一定是一个简单的解决方案......然而,我找不到它。
我该怎么做?
提前致谢。
使用 this.add()
而不是 Gamelabel.add()
。
你不能调用 Gamelabel.add()
因为要调用 Gamelabel.add()
在 Gamelabel
class 中应该有一个静态方法 add()
但 Gamelabel 有一个继承实例方法 add()
不是静态方法。
public void Gamelabel() {
JLabel mylabel = new JLabel();
mylabel.setBounds(0, 0, 1280, 720);
mylabel.setVisible(true); //unnecessary
this.add(mylabel);
}
也使用布局管理器。在您的代码中,您不能使用 setBounds()
方法,因为面板布局是流动的(默认)。setbounds
在不使用布局管理器时用于绝对定位。所以请阅读如何使用 layout managers and flow layout .
也不需要 mylabel.setVisible(true);
因为 jlable
默认可见,不像 jframe
.
如标题所述,我想将 JLabel 添加到扩展 JPanel 的 class(在我的例子中,命名为 GamePanel)。我试过
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
*
*/
}
所以我真的不知道该怎么做,但我觉得这一定是一个简单的解决方案......然而,我找不到它。
我该怎么做? 提前致谢。
使用 this.add()
而不是 Gamelabel.add()
。
你不能调用 Gamelabel.add()
因为要调用 Gamelabel.add()
在 Gamelabel
class 中应该有一个静态方法 add()
但 Gamelabel 有一个继承实例方法 add()
不是静态方法。
public void Gamelabel() {
JLabel mylabel = new JLabel();
mylabel.setBounds(0, 0, 1280, 720);
mylabel.setVisible(true); //unnecessary
this.add(mylabel);
}
也使用布局管理器。在您的代码中,您不能使用 setBounds()
方法,因为面板布局是流动的(默认)。setbounds
在不使用布局管理器时用于绝对定位。所以请阅读如何使用 layout managers and flow layout .
也不需要 mylabel.setVisible(true);
因为 jlable
默认可见,不像 jframe
.