Java Object method is not working
Good day!
I have two objects namely PLAYER AND GAME.. The player consists of variable String playerName
. In the Player Object I have a method public String getPlayer();
wherein a when you typed in a text in the text box, you can get the name.
I need to access the name in the GAME Object. But I cannot access it. My code is as follows:
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 g开发者_开发百科etPlayer() {
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();
}
May I know what i am doing wrong? Any help will be highly appreciated. Thank you.
You say:
"In the Player Object I have a method public String getPlayerName();
"
while no such thing exists in your code. Perhaps you meant public String getPlayer()
, since that method exists.
Also, take a look at your existing method:
public String getPlayer() {
playerName = txtPlayerName.getText();
System.out.println(playerName);
return playerName;
}
Above it you have:
private String playerName;
In your getPlayer()
method, you're accessing txtPlayerName
which doesn't exist. You probably meant
this.playerName = playerName.getText();
although this won't solve your problem fully, since nowhere do I see a method that accesses the external playerName
(txtPlayerName
in your code).
Now that I've pointed out a few observations, I'm sure you can handle the rest.
You using the default constructor, which does not initialize the components:
Player playerName = new Player();
This could be a problem.
Then, of course, txtPlayerName
is not defined in the code snippet.
Finally - your confusing yourself and the other with variable and method names ;) Please rename the getter Method in Player
to getPlayerName()
(because you do return the players name) and the local variable playerName
in the MainGame
constructor to player
(because now you create the Player
dialog.
BTW - you don't show the Player
dialog. Another chance for a solution to the problem. Call playerName.setVisible(true)
and allow the user to enter a name.
Responding to a comment
Player
has two constructors, the default constructor (no arguments) and another one (takes an instance of JFrame
). The other constructor calls the magic method initComponents()
and the default constructor dosn't. I don't know what has to be initialized, but this step is missing if you create a Player
dialog with the default constructor.
I think we should ask him what he meant by I can not access it
.
What is the exception or compile error you are getting, and on what line.
精彩评论