gpt4 book ai didi

java - 如何检查 JTextField 是否为空?

转载 作者:行者123 更新时间:2023-12-01 07:03:00 24 4
gpt4 key购买 nike

如何检查 JTextfield 是否为空以返回 true 或 false 并设置焦点?我尝试检查该字段是否等于 null,但这不起作用。我所做的与这个问题相关的操作可以在注释 //这部分代码 及其下面的 boolean 值

下找到
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
}

最佳答案

JTextField#getText#isEmpty...

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

JTextFiels#getText 已经很长时间没有返回 null

您可能还想查看Validating Input这可能会容易得多

关于java - 如何检查 JTextField 是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com