【问题标题】:Edit JLabel text inside a method在方法内编辑 JLabel 文本
【发布时间】:2018-04-03 20:44:12
【问题描述】:

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

现在我想在同一个类的方法中编辑标签的文本,但我不确定该怎么做。我是否必须在方法内部创建像 ScorePlayer scorePlayer = new ScorePlayer(); 这样的对象实例?

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

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 scoreglobal 设为:

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

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

【问题讨论】:

  • 不,您不想这样做,因为您将修改 wrong 对象/实例的状态。您想要修改当前显示的 ScorePlayer 实例的状态(JLabel 上的文本)。这要求您了解什么是实例或对象,以及它与变量的区别。
  • 过去几周我对这个话题了解了很多,但是这个问题让我达到了极限。
  • 我的建议:取消这篇文章——你似乎来得太早了——试着看看你能做什么。请记住尝试更改可视化 GUI 的状态,而不是新的单独的,避免为此使用静态变量,研究类似的问题,看看你能想出什么。

标签: java swing jpanel jlabel


【解决方案1】:

根据您的问题,我了解到您需要添加一个 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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    相关资源
    最近更新 更多