0

I've created a custom JtextField but any proprety defined method don't working like getText or SetText when I call it in the main JFrame.

import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class JTextFieldDecimal extends JTextField {
    private static final long serialVersionUID = 1L;
public JTextFieldDecimal()
{
    super();
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            char c =e.getKeyChar();
            if(!((c>='0') && (c<='9') || 
                    (c==KeyEvent.VK_BACK_SPACE) ||
                    (c==KeyEvent.VK_DELETE)))
            {
                getToolkit().beep();
                e.consume();
            }

        }
    });

}
}

enter image description here

when I click in validation button in jframe Produit the compiler give me an error and point to line 98 wich content my statement parameter of Custom JtextField named txtPrixHT.

btnValider.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
            Connection cn=null;
            PreparedStatement pst =null;
            ResultSet rs=null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                cn=DriverManager.getConnection("jdbc:mysql://localhost/gesticom", "root","");
                //String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT,PrRemise,PrPrixAchat,PrStockAlerte,PrStockReel) values (?,?,?,?,?,?,?)";
                String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT) values (?,?,?)";
                pst=cn.prepareStatement(sqlAdd,Statement.RETURN_GENERATED_KEYS);
                pst.setString(1, txtCodebarre.getText());
                pst.setString(2, txtDesignation.getText());
                pst.setString(3,txtPrixHT.getText());
                pst.execute();
                rs=pst.getGeneratedKeys();
                if(rs.next())
                {
                    txtIdprod.setText(rs.getString(1));
                    JOptionPane.showMessageDialog(null, "Nouveau Produit créé", "Fournisseur",JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally {
                try
                {
                    cn.close();
                    pst.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            }
        });
  • 2
    The error doesn't occur in this part of the code, please add the relevant part of the `Produit` class (including the line 98 ) . – Arnaud May 14 '18 at 09:57
  • 1
    By the way, I would not mess to much with the `JTextField` key adapter. You consume the event but are you sure you have the priority ? `JTextField` use a `Document` to manage the input if I remember it correctly. – AxelH May 14 '18 at 10:05
  • `txtPrixHT` must be `null` at line 98 . – Arnaud May 14 '18 at 10:15
  • I had fill txtPrixHT by value it's not null – IT dev java May 14 '18 at 10:19
  • Use the debugger to make sure this is using the `txtPrixHT` instance that is added to the GUI. If this is the line that throw the NPE, this is the most obvious reason. – AxelH May 14 '18 at 10:21

1 Answers1

1

For an alternative to your formatted text field, I would propose you don't try to validate the input yourself. You can use a JFormattedTextField that allow you to do it for you when the focus is lost. Here is a quick sample

JFormattedTextField decimalTxt = new JFormattedTextField(
    new NumberFormatter()
);

This will use the Locale of the JVM to format the number like expected (simpler for Decimal values). If you want only to take integers, provide an integer format

JFormattedTextField decimalTxt = new JFormattedTextField(
    new NumberFormatter(
        NumberFormat.getIntegerInstance()
    )
);

You want to always have two decimal digit like 5.00, define it in the NumberFormat :

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);

JFormattedTextField decimalTxt = new JFormattedTextField(
    new NumberFormatter(nf)
);

You can find more information about this on How to Use Formatted Text Fields

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • thank for answers deer dev, i do miske when i declare my Custom JtextField, my Error at: JTextFieldDecimaltxtPrixHT = new JTextFieldDecimal() then the first word JTextFieldDecimaltxtPrixHT in declaration must be removed – IT dev java May 14 '18 at 11:01
  • @ITdevjava you forgot a space ... `JTextFieldDecimaltxtPrixHT` > `JTextFieldDecimal txtPrixHT` for the rest, I don't understand your problem. – AxelH May 14 '18 at 11:37