从另一个JTextField
读取String
后,在另一个类中更新JTextField
时遇到一些问题。这是有问题的方法:
public JTextField buyVowel(playerPlate player)
{
String get = input.getText();
String[] vowels = new String[]{"a","e","i","o","u"};
for(int i =0; i<vowels.length; i++)
{
if(get.equals(vowels[i]))
{
player.pMoney =- 250;
player.playerMoney.setText("$"+player.pMoney);
}
}
return player.playerMoney;
}
playerPlate
是一个单独的类。我正在使用此方法来确定程序应修改的播放器:
public playerPlate getCurrentPlayer()
{
if(currentPlayer == 1)
{
return player1;
}
else if(currentPlayer == 2)
{
return player2;
}
else
{
return player3;
}
}
播放器1、2和3是
playerPlate
的实例。我希望它正在修改此类中的实例变量:
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class playerPlate extends JPanel
implements ActionListener
{
public String pName;
public int pMoney = 500;
public int currentPlayer;
public JTextField playerMoney;
public playerPlate(String player, Color color, int currentPlayer)
{
setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
setBackground(color);
pName = player;
JTextField playerNames = new JTextField(pName);
playerNames.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
playerNames.setEditable(false);
playerNames.setFont(new Font("Impact", Font.PLAIN, 24));
playerNames.setHorizontalAlignment(JTextField.CENTER);
playerNames.setBackground(Color.WHITE);
JTextField playerMoney = new JTextField("$"+pMoney);
playerMoney.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
playerMoney.setEditable(false);
playerMoney.setFont(new Font("Impact", Font.BOLD, 32));
playerMoney.setHorizontalAlignment(JTextField.CENTER);
playerMoney.setBackground(Color.WHITE);
Box b1 = Box.createVerticalBox();
b1.add(playerNames);
b1.add(Box.createVerticalStrut(5));
Box b2 = Box.createHorizontalBox();
b2.add(Box.createHorizontalStrut(60));
Box b3 = Box.createVerticalBox();
b3.add(playerMoney);
b3.add(Box.createVerticalStrut(8));
b2.add(b3);
b1.add(b2);
b1.add(Box.createVerticalStrut(5));
add(b1);
}
public void actionPerformed(ActionEvent e)
{
}
}
这是主类中的
actionPerformed
方法:public void actionPerformed(ActionEvent e)
{
JButton b = (JButton)e.getSource();
if(b==spin)
{
spinWheel(wheelStuff);
repaint();
}
if(b==next)
{
updatePlayer();
repaint();
}
if(b==reset)
{
letterBoard.reset();
updateCat();
repaint();
}
if(b==buyVowel)
{
buyVowel(getCurrentPlayer());
repaint();
}
}
我要发生的要点是,当用户在
JTextField input
中键入一个元音,然后单击JButton buyVowel
时,将从其总金额(pMoney
)中减去$ 250。并在GUI上显示更改。修改了几个小时之后,老实说,我不知道为什么这不起作用。尝试使用它时,我一直收到nullPointerExceptions
。谢谢你的帮助。注意:除类
playerPlate
之外的所有内容都在同一类中。 playerPlate
在单独的类中。 最佳答案
您是playerMoney
构造函数中的shadowing变量playerPlate
。方法buyVowel
依赖于调用playerPlate
时实例化的setText
,否则将抛出NullPointerException
。更换
JTextField playerMoney = new JTextField("$"+pMoney);
与
playerMoney = new JTextField("$"+pMoney);
另外:Java命名约定表示类名以大写字母开头,因此请使用诸如
PlayerPlate
之类的类名。