Como verificar se um jTextField está vazio ou não, ou se tem números/letras, etc??
aqui segue o código onde tenho que verificar se o jTextField está vazio:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (tempTextField esta vazio????????)
{
//Parse degrees Celsius as a double and convert to Fahrenheit.
int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
else
{
String er = "Não há temperatura!";
fahrenheitLabel.setText(er);
}
}
Explicando em detalhes:
O método JTextField.getText() retorna a String que está no text field.
E o método String.equals(String arg) verifica se as Strings são iguais.
É só verficar se o texto é igual a String vazia “”.
textField.getText().equals("")
[quote=wellington7]Explicando em detalhes:
O método JTextField.getText() retorna a String que está no text field.
E o método String.equals(String arg) verifica se as Strings são iguais.
É só verficar se o texto é igual a String vazia “”.
textField.getText().equals("")[/quote]
[quote=renzonuccitelli]private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
if ("".equals(tempTextField.getText())&&equals(tempTextField.getText()!=null)
{
//Parse degrees Celsius as a double and convert to Fahrenheit.
int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
else
{
String er = "Não há temperatura!";
fahrenheitLabel.setText(er);
}
}[/quote]
Valeu galera!!!
funcionou
=]
Eu jamais usaria “”, pra representar null, sinal de que to longe de ser programador java ainda^^
o renzonuccitelli, colocou outro condição, a equals(tempTextField.getText()!=null, eu testei sem ela e funcionou tb, tem algum problema se eu deixar sem essa condição?
segue o código:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (!"".equals(tempTextField.getText()))
{
//Parse degrees Celsius as a double and convert to Fahrenheit.
int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
else
{
String er = "Não há temperatura!";
fahrenheitLabel.setText(er);
fahrenheitLabel.setForeground(Color.RED);
}
}
tipo, se nao me engano o TextField não retorna null e sim vazio qdo o usuário não o preenche. Por isso eu usei o vazio “” em vez de nulo. Fica trankilo que não são esses detalhes que fazem de vc um bom programador ou não. O que importa é a lógica, essas outras coisas vc aprende errando. Só sei isso pq precisei fazer a mesma coisa certa vez com um TextField…
[quote=ton.]
mas tem como eu colocar um aviso, tipo uma dialog informando que a pessoa ta inserindo os dados de forma errada?[/quote]
Crie um novo topico para a nova pergunta…
tipo:
public class ValidaText extends Validator{ @Override
public Result validate(Object value) {
if(value.equals("")){
return new Result(null, “Camplo vazio. Informe=o.”);
}else return null;
}
}