Search code examples
javaswingdatejtextfieldjformattedtextfield

How to take date in Text field


I am new to Java and I'm having trouble getting the date format for a Textfield. I'd like to take the date input by the user and input it into a database. I've tried using JCalender but it's not working because I failed to configure the palette. Are there any other options other than JCalender? Thanks in advance.

Here is what I have so far:

// Delivery Date Action

              tf3.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_SLASH)))        
      {
        JOptionPane.showMessageDialog(null, "Please Enter Valid");
        e.consume();
      }
    }
  });


        tf3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
               int i = Integer.parseInt(tf3.getText());


            }

Solution

  • JFormattedTextField is a subclass of JTextField.
    
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    JFormattedTextField txtDate = new JFormattedTextField(df);
    

    you can add validation event on it

    txtDate .addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
          char c = e.getKeyChar();
          if (!((c >= '0') && (c <= '9') ||
             (c == KeyEvent.VK_BACK_SPACE) ||
             (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_SLASH)))        
          {
            JOptionPane.showMessageDialog(null, "Please Enter Valid");
            e.consume();
          }
        }
      });