Search code examples
javaswingjtextfield

How to check if a JTextField is empty?


How do I check to see if the JTextfield is empty to return true or false and set the focus? I have tried checking to see if the field is equal to null but that does not work. What I have done that pertains to this question can be found under the comment // THIS SECTION OF CODE and the boolean below it

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DollarStore extends Applet  implements ActionListener 

{

 public JLabel      n1  = new JLabel("Enter sales person number (1-4): ");
 public JTextField  tf1 = new JTextField(5);
 public JLabel      n2  = new JLabel("Enter product number (1-5): ");
 public JTextField  tf2 = new JTextField(5);
 public JLabel      n3  = new JLabel("Enter sales amount (0.01-0.99): ");
 public JTextField  tf3 = new JTextField(5);
 public JTextArea   ta  = new JTextArea (8,58);
 public JButton     s   = new JButton ("Submit");
 public JButton     c   = new JButton ("Clear");

  public void init()
  {
  setLayout(new FlowLayout(FlowLayout.CENTER, 10, 20));

add(n1);
add(tf1);
add(n2);
add(tf2);
add(n3);
add(tf3);
ta.setFont(new Font("Courier", Font.BOLD, 10));
ta.setEditable(false);
add(ta);
add(s);
add(c);

s.addActionListener(this);
c.addActionListener(this);
}

// THIS SECTION OF CODE
private boolean emptyFields()
{
if (tf1.getText() == null)
{
 tf1.requestFocus();
 return true;
}
if (tf2.getText() == null)
{
 tf2.requestFocus();
 return true;
}
if (tf3.getText() == null)
{
 tf3.requestFocus();
 return true;
}

 return false;


 } // End emptyFields

public void actionPerformed(ActionEvent e)
{
   // Variables for TextField 
 int    spnumber = Integer.parseInt(tf1.getText());
 int    pnumber  = Integer.parseInt(tf2.getText());
 double sanumber = Double.parseDouble(tf3.getText());

if (e.getSource() == c)
{
  tf1.setText("");
  tf2.setText("");
  tf3.setText("");
  tf1.requestFocus();
}

if (e.getSource() == s)
{
emptyFields();

 {
  if (spnumber < 1 || spnumber > 4)
   showStatus("Sales person number must be in the range 1 to 4");
   if (pnumber < 1 || pnumber > 5)
   showStatus("Product number must be in the range 1 to 5");
   if (sanumber < 0.01 || sanumber > 0.99)
   showStatus("Product number must be in the range 0.01 to 0.99");
 }
 }
}  // End actionPerformed
}

Solution

  • JTextField#getText#isEmpty...

    if (tf1.getText().trim().isEmpty()) {
        ...
    }
    

    It's been a very long time since JTextFiels#getText could return null

    You might also like to have a look at Validating Input which would probably be significantly easier