如何检查JTextField是否为空?

时间:2016-03-28 23:36:49

标签: java swing jtextfield

如何检查JTextfield是否为空以返回true或false并设置焦点?我已经尝试检查该字段是否等于null但是这不起作用。我可以在评论// THIS SECTION OF CODE及其下方的布尔值

下找到与此问题有关的内容。
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
}

2 个答案:

答案 0 :(得分:6)

JTextField#getText#isEmpty ...

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

JTextFiels#getText返回null

以来已经过了很长时间

您可能还想查看Validating Input,这可能会非常容易

答案 1 :(得分:2)

试试这个:

if (tf1.getText().equals("")) {
    //set true or false
}