1
Good afternoon guys, I’m not able to validate the field type value double
The field I cannot validate for the registration is the field valor
.
Follows the class method to validate the data to register:
public boolean verificaDados(CardapioBeans cardapio, String valor){
if(cardapio.getDescricao().equals("")){
JOptionPane.showMessageDialog(null, "Campo Descrição nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
return false;
}
if(valor.equals("")){
JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
return false;
}
cardapioD.cadastrarCardapio(cardapio);
return true;
}
Follows the method cadastrarCardapio
:
public void cadastrarCardapio(CardapioBeans cardapio){
try {
String SQLInsertion = "insert into cardapio(car_descricao, car_tipo, car_valor) "
+ "values(?,?,?);";
PreparedStatement stm = Conexao.getConnetion().prepareStatement(SQLInsertion);
stm.setString(1, cardapio.getDescricao());
stm.setString(2, cardapio.getTipo());
stm.setDouble(3, cardapio.getValor());
stm.execute();
Conexao.getConnetion().commit();
JOptionPane.showMessageDialog(null, "cadastrado com sucesso!","cadastro efetivado",1,new ImageIcon("Imagens/sucess.png"));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Impossivel cadastrar","Erro de SQL", 0, new ImageIcon("Imagens/cancelar.png"));
}
}
Follow the Event B_CadastrarActionPerformed
:
private void B_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {
capturaBeans();
// se for true entra no if
if(cardapioC.verificaDados(cardapioB, TF_Valor.getText())){
limparTudo();
habilitaTudo(false); // campos desabilitados para digitar
}
}
Follow the method that captures screen data:
final CardapioBeans capturaBeans(){
cardapioB.setCodigo(Integer.parseInt(TF_Codigo.getText()));
cardapioB.setDescricao(TA_Descricao.getText());
cardapioB.setTipo(CB_Tipo.getSelectedItem().toString());
cardapioB.setValor(Double.parseDouble(TF_Valor.getText()));
return cardapioB;
}
Follow the error when I click the sign up button:
run: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842) at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.lang.Double.parseDouble(Double.java:538) at GUI.CardapioGUI.capturaBeans(CardapioGUI.java:387) at GUI.CardapioGUI.B_CadastrarActionPerformed(CardapioGUI.java:294) at GUI.CardapioGUI.access$400(CardapioGUI.java:10) at GUI.CardapioGUI$6.actionPerformed(CardapioGUI.java:118) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6525) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6290) at java.awt.Container.processEvent(Container.java:2234) at java.awt.Component.dispatchEventImpl(Component.java:4881) at java.awt.Container.dispatchEventImpl(Container.java:2292) at java.awt.Component.dispatchEvent(Component.java:4703) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462) at java.awt.Container.dispatchEventImpl(Container.java:2278) at java.awt.Window.dispatchEventImpl(Window.java:2750) at java.awt.Component.dispatchEvent(Component.java:4703) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) CONSTRUÍDO COM SUCESSO (tempo total: 35 segundos)
Follows the code that validates if the user enters a string But I’m trying to do how to validate the value field that is double type, Imagine q the user clicked on register and forgot to fill the value field of double type. I can not implement, obg
private void TF_ValorFocusLost(java.awt.event.FocusEvent evt) {
try{
double verifica = Double.parseDouble(TF_Valor.getText().replace(',','.'));
TF_Valor.setText(formatoDecimal.format(verifica).replace(',', '.'));
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Campo Valor Deve Conter Apenas Números","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
TF_Valor.setText("");
TF_Valor.requestFocus();
}
}
Follows the Nullpointerexception error: which happens in the Cardapiogui and Cardapiocontroller class in the verified method()
import Beans.CardapioBeans;
import Controller.CardapioController;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class CardapioGUI extends javax.swing.JInternalFrame {
DefaultTableModel modelo;
CardapioController cardapioC;
CardapioBeans cardapioB;
DecimalFormat formatoDecimal;
public CardapioGUI() {
initComponents();
TF_Codigo.setEditable(false);
habilitaTudo(false);
modelo = (DefaultTableModel)Tabela.getModel();
cardapioC = new CardapioController();
cardapioB = new CardapioBeans();
formatoDecimal = new DecimalFormat("0.00");
}
private void B_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {
//capturaBeans();
// se for true entra no if
if(cardapioC.verificaDados(cardapioB, TF_Valor.getText())){
capturaBeans();
limparTudo();
habilitaTudo(false); // campos desabilitados para digitar
}
}
Cardapio controller :
public boolean verificaDados(CardapioBeans cardapio, String valor){
if(cardapio.getDescricao().equals("")){
JOptionPane.showMessageDialog(null, "Campo Descrição nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
return false;
}
if(valor.equals("")){
JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
return false;
}
try {
Double.parseDouble(valor);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Campo Valor não é um número","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
return false;
}
cardapioD.cadastrarCardapio(cardapio);
return true;
}
The field
carValor
Do you accept null in the database? The method iscardapioB.setValor(Double)
orcardapioB.setValor(double)
? I mean, he usesdouble
lower case letter orDouble
capital letter?– Victor Stafusa
Ah, you should use the Try-with-Resources in his
PreparedStatement
. The way it is, if there’s oneSQLException
, it will not be closed properly. See more here.– Victor Stafusa
If it’s monetary value, you can start by not using
double
since this is an error. http://answall.com/q/77746/101– Maniero
Much of this validation could have been eliminated using Jformattedtextfield. The end user experience is also much better since the feedback is immediate (it doesn’t need to submit the form). You can use your
DecimalFormat
(withsetParseBigDecimal(true)
see bigown advice) and a standard value (e.g.,0.00
) to initialize theJFormattedTextField
. With this the value will never be empty, will always be valid and you can recover the desired type (BigDecimal
,Double
, etc) withgetValue()
.– Anthony Accioly