gpt4 book ai didi

Java 对象方法不起作用

转载 作者:行者123 更新时间:2023-12-02 00:46:33 25 4
gpt4 key购买 nike

美好的一天!

我有两个对象,即玩家和游戏。玩家由变量StringplayerName组成。在播放器对象中,我有一个方法public String getPlayer();,其中当您在文本框中输入文本时,您可以获得名称。

我需要访问游戏对象中的名称。但我无法访问它。我的代码如下:

玩家:

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;
}

}

游戏:

public class MainGame extends JDialog implements ActionListener {

public MainGame(JDialog owner) {
super(owner, true);
initComponents();
Player playerName = new Player();
pName.setText(playerName.getPlayer());
newGame();
}

我可以知道我做错了什么吗?任何帮助将不胜感激。谢谢。

最佳答案

你说:

“在玩家对象中,我有一个方法 public String getPlayerName();

虽然您的代码中不存在这样的东西。也许您的意思是 public String getPlayer(),因为该方法存在。

另外,看看您现有的方法:

public String getPlayer() {
playerName = txtPlayerName.getText();
System.out.println(playerName);
return playerName;
}

在它上面你有:

private String playerName;

在您的 getPlayer() 方法中,您正在访问不存在的 txtPlayerName。你的意思可能是

this.playerName = playerName.getText();

尽管这不能完全解决您的问题,因为我没有看到访问外部 playerName 的方法(代码中的 txtPlayerName)。

现在我已经指出了一些观察结果,我相信您可以处理其余的问题。

关于Java 对象方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4848851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com