Frage

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());


            }
War es hilfreich?

Lösung 2

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();
      }
    }
  });

Andere Tipps

You can put three different Drop Down Boxes to specify Day, Month and Year. You need not to check for other validations. If 31 date is possible for that month, Leap year check and Order Date < Delivery Date.

Based on Mohammod Hossain's answer, I have written this simple class. I hope it can help.

public class JDateTextField extends JFormattedTextField{

private final String format;
private final char datesep;
private Component pare = null;

/**
 * Establece el componente padre para los mensajes de dialogo.
 * <p>
 * @param pare
 */
public void setPare(Component pare) {
    this.pare = pare;
}

public JDateTextField(final String format) {
    super(new SimpleDateFormat(format));
    this.format = format;
    setColumns(format.length());
    //if(format.contains("-")) datesep=KeyEvent.VK_MINUS;
    //else
    if (format.contains("/")) {
        datesep = KeyEvent.VK_SLASH;
    } else {
        datesep = KeyEvent.VK_MINUS;
    }

    addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            try {
                Date date = getDate();
            } catch(ParseException ex) {
                showError("Por favor introduzca una fecha válida.");
            }
        }
    });
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            String s = "" + c;
            if (s.matches("|[a-z]|i")){
                showError("Carácter no válido detectado " + s);
                e.consume();
            } else if(!((c >= '0') && (c <= '9')
                    ||(c == KeyEvent.VK_BACK_SPACE)
                    ||(c == KeyEvent.VK_DELETE)
                    ||(c == datesep)||(c == KeyEvent.VK_COLON))){
                showError("Carácter no válido detectado " + c);
                e.consume();
            }
            /*
             * else{
             * try{
             * Date date=getDate();
             * }catch(ParseException ex){
             * showError("Por favor introduzca una fecha válida.");
             * }
             * }
             */
        }
    });
    setValue(new Date());
}

private void showError(String error) {
    JOptionPane.showMessageDialog(pare, error + "\n\tEl patrón válido es: " + format, "Fecha NO válida", JOptionPane.ERROR_MESSAGE);
}

public Date getDate() throws ParseException {
    SimpleDateFormat frt = new SimpleDateFormat(format);
    return frt.parse(getText());
}

}

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top