2011-01-31 44 views
0

美好的一天!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(); 
    } 

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

+0

是`txtPlayerName.getText()`在你的`Player`类中出现错字?我从来没有在其他地方看到它。 – sarnold 2011-01-31 08:27:19

+0

@sarnold txtPlayerName是一个JtextField,使用Netbean的GUI生成 – newbie 2011-01-31 08:57:45

+0

啊,谢谢;你可能不希望有一个对象的getter方法从文本字段中检索值,该文本字段可能存在或不存在于任何特定的视图中,并且天堂禁止你可能希望有一天在你的游戏中有两个玩家。 :)我建议使用从GUI中检索到的玩家名称来初始化玩家对象,并将GUI的知识保留在你的`Player`类中,只要它有意义。 – sarnold 2011-01-31 09:04:51

回答

2

你说:

“中玩家的对象我有一个方法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(); 

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

既然我已经指出了一些观察,我相信你可以处理其余的。

+0

textPlayerName是一个文本字段...如果我在那里输入文本,我想获取文本... – newbie 2011-01-31 08:51:55

1

您使用默认的构造函数,它不初始化组件:

Player playerName = new Player(); 

可能是一个问题。

然后,当然,txtPlayerName未在代码段中定义。

最后 - 你混淆自己和其他与变量和方法名;)请Player getter方法重命名为getPlayerName()(因为你做回球员的名字)和局部变量playerNameMainGame构造函数player(因为现在创建Player对话框

顺便说一句 - 你不会显示对话框Player。解决问题的另一个机会,请致电playerName.setVisible(true)并允许用户输入名称。


回应评论

Player有两个构造中,默认构造函数(无参数)和另一个(需要的JFrame一个实例)。 其他构造函数调用魔术方法initComponents()和默认构造函数dosn't。我不知道必须初始化什么,但如果使用默认构造函数创建Player对话框,则会丢失此步骤。

0

我想我们应该问他他的意思是I can not access it

什么是你遇到的异常或编译错误,以及在什么行。