在方法内编辑JLabel文本

时间:2018-04-03 20:44:12

标签: java swing jpanel jlabel

我创建了一个ScorePlayer类,扩展了JPanel并在构造函数中添加了JLabel分数。

现在我想在同一个类的方法中编辑Label的Text,但我不确定如何做到这一点。我是否必须在方法内部创建对象的实例,如ScorePlayer scorePlayer = new ScorePlayer();

EDIT 首先,感谢您的帮助。 我刚刚在我的构造函数中为Label创建了一个局部变量,如:

ScorePlayer(String playerName) {
    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 1;
    setPreferredSize(new Dimension(Var.scoreBoardWidth, 200));
    JLabel player = new JLabel();
    player.setFont(new Font("Arial", 0, 32));
    JLabel score = new JLabel(); 
    score.setFont(new Font("Arial", 0, 32)); 
    score.setText(Integer.toString(spielStand));
    add(player, gbc);
    gbc.gridy = 2;
    add(score, gbc);
}

现在,我刚刚将JLabel score全局化为:

JLabel score = new JLabel();
ScorePlayer() {
 //CODE
}

这只是一个愚蠢的初学者的错误。

1 个答案:

答案 0 :(得分:0)

根据您的问题,我了解您需要添加JLabel的实例,之后您的课程将如下所示

public class ScorePlayer {
      private JLabel labelOne;

 public ScorePlayer (JLabel label){
         this.labelOne = label;
   }//this is where you initialize a JLabel object

添加这些代码行后,您必须像这样添加方法setLabel

public void setLabel(String label){
    labelOne.setText(label);
 }// this is inside your ScorePlayer class

我希望这会对你有所帮助。

相关问题