美好的一天!Java对象方法不起作用
我有两个对象,即PLAYER AND GAME ..玩家由变量String playerName
组成。在玩家对象中,我有一个方法public String getPlayer();
其中一个当你在文本框中输入一个文本时,你可以得到这个名字。
我需要访问GAME对象中的名称。但我无法访问它。我的代码如下:
PLAYER:
public class Player extends javax.swing.JDialog {
private String playerName;
public Player(JFrame owner) {
super(owner, true);
initComponents();
}
public Player() {
this(null);
}
public String getPlayer() {
playerName = txtPlayerName.getText();
System.out.println(playerName);
return playerName;
}
}
GAME:
public class MainGame extends JDialog implements ActionListener {
public MainGame(JDialog owner) {
super(owner, true);
initComponents();
Player playerName = new Player();
pName.setText(playerName.getPlayer());
newGame();
}
我可以知道我做错了什么?任何帮助将不胜感激。谢谢。
是`txtPlayerName.getText()`在你的`Player`类中出现错字?我从来没有在其他地方看到它。 – sarnold 2011-01-31 08:27:19
@sarnold txtPlayerName是一个JtextField,使用Netbean的GUI生成 – newbie 2011-01-31 08:57:45
啊,谢谢;你可能不希望有一个对象的getter方法从文本字段中检索值,该文本字段可能存在或不存在于任何特定的视图中,并且天堂禁止你可能希望有一天在你的游戏中有两个玩家。 :)我建议使用从GUI中检索到的玩家名称来初始化玩家对象,并将GUI的知识保留在你的`Player`类中,只要它有意义。 – sarnold 2011-01-31 09:04:51