[英]Edit JLabel text inside a method
I've created a ScorePlayer
class which extends JPanel
and added a JLabel
score in the constructor. 我创建了一个
ScorePlayer
类,该类扩展了JPanel
并在构造函数中添加了JLabel
得分。
Now I want to edit the Text of the Label in a method of the same class but I am not really sure how to do it. 现在,我想在同一类的方法中编辑标签的文本,但我不确定如何执行。 Do I have to create an Instance of the Object like
ScorePlayer scorePlayer = new ScorePlayer();
我是否必须创建对象的实例,例如
ScorePlayer scorePlayer = new ScorePlayer();
inside of the method? 里面的方法?
EDIT First of all, thanks for your help. 编辑首先,感谢您的帮助。 I've just created a local variable for the Label in my Constructor like:
我刚刚在构造函数中为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);
}
Now, I just made JLabel score
global like: 现在,我刚刚将
JLabel score
全球水平,例如:
JLabel score = new JLabel();
ScorePlayer() {
//CODE
}
It was just a silly beginner's mistake. 这只是一个愚蠢的初学者的错误。
From your question i understand that you will need to add a instance of a JLabel
and after this your class will look like this 根据您的问题,我知道您将需要添加
JLabel
的实例,并且在此之后,您的类将如下所示
public class ScorePlayer {
private JLabel labelOne;
public ScorePlayer (JLabel label){
this.labelOne = label;
}//this is where you initialize a JLabel object
after you add those lines of code you have to add method setLabel
like this 添加这些代码行后,您必须添加方法
setLabel
如下所示
public void setLabel(String label){
labelOne.setText(label);
}// this is inside your ScorePlayer class
I hope this will help you. 我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.