Как проверить, нет ли JTextfield
, чтобы вернуть true или false и установить фокус? Я попытался проверить, соответствует ли поле нулю, но это не работает. То, что я сделал, что имеет отношение к этому вопросу можно найти в комментарии // THIS SECTION OF CODE
и булевы ниже егоКак проверить, пуст ли JTextField?
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' ... Вам также может понравиться [Validating Input] (http: // docs .oracle.com/javase/tutorial/uiswing/misc/focus.html # inputVerification), который, вероятно, будет значительно проще. – MadProgrammer
Вы можете поместить свои JTextFields в массив и перебрать его. –
Попробуйте http://stackoverflow.com/questions/17132452/java-check-if-jtextfield-is-empty-or-not? Кажется, ваш вопрос. –