Reputation: 3
public void testDialog()
{
JPanel myPanel = new JPanel();
JTextField tfNames [] = new JTextField[getNumOfPlayers()];
for(int i=0;i < getNumOfPlayers();i++)
{
tfNames[i] = new JTextField(20);
myPanel.add(new JLabel("Player " + (i+1)));
myPanel.add(tfNames[i]);
}
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter The Player Names", JOptionPane.OK_CANCEL_OPTION);
playerNames = new String [getNumOfPlayers()];
if(result == JOptionPane.OK_OPTION)
{
for(int i=0;i < getNumOfPlayers();i++)
{
if(tfNames[i].getText() == null)
{
//NOT GETTING INSIDE HERE FOR ONE REASON OR ANOTHER
System.out.println("NULL FIELD" + i);
testDialog();
}
else
{
playerNames[i] = tfNames[i].getText();
System.out.println(playerNames[i]);
}
}
}
else if (result == JOptionPane.CANCEL_OPTION)
{
numPlayersDialog();
}
else
{
numPlayersDialog();
}
}
Basically I'm trying to check if one of the textFields are blank when the 'OK' button is clicked and if it is recall this method again but for some reason it never gets inside the piece of the code checking to see whether the textField is null or not it skips straight over it everytime even if it is null :/ Can anyone explain why? Set for an hour trying to figure it out and haven't been able to find a reason for it :/ Thanks, for any advice you may have.
PS. If there is away of disabling the 'OK' button while one of more of the textFields are blank please let me know.
Upvotes: 0
Views: 51
Reputation: 13713
That is because text will never be null, it will be empty so just change your check to :
if (tfNames[i].getText().isEmpty()) {
}
if using sdk lower than 1.6 than use the plain ole checking : tfNames[i].getText().equals("")
Upvotes: 1
Reputation: 55750
Because most likesly tfNames[i].getText()
returns an empty string, not null
.
Maybe you should check for that instead:
if(tfNames[i].getText() != null && tfNames[i].getText().isEmpty()){
// ...
}
Upvotes: 1