Frage

I'm creating a frame with a JFormattedTextField masked with MaskFormatter:

public static void main(String[] args) {
    DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
    JFrame frame = new JFrame("");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    frame.setLayout(new BorderLayout());
    JFormattedTextField tf = new JFormattedTextField(df);
    tf.setColumns(20);
    panel.add(tf);
    try {
        MaskFormatter dateMask = new MaskFormatter("##-##-####");
        dateMask.install(tf);
    } catch (ParseException ex) {
        Logger.getLogger(MaskFormatterTest.class.getName()).log(Level.SEVERE, null, ex);
    }

    frame.add(new JButton(), BorderLayout.LINE_START);

    frame.add(panel, BorderLayout.LINE_END);
    frame.pack();
    frame.setVisible(true);
}

OK. It's alright, but when i delete (with keyboard key) the text i write in the field too delete slashes. Are there any mode to prevent it? I want delete the text but the slashes not, like:

Writing date:

"12-12-1212"

After delete:

"  -  -    "
War es hilfreich?

Lösung

How do you delete the text? Are you using setText("")? You should not do that. Use setValue(null) instead. If that is not your problem, please elaborate on what you are doing, and what is happening instead.

edit: Try out this code and see if the problem persists.

public class Tester {
  public static void main(String[] args) {
    DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
    JFrame frame = new JFrame("");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    frame.setLayout(new BorderLayout());
    JFormattedTextField tf = new JFormattedTextField(df);
    tf.setFocusLostBehavior(JFormattedTextField.COMMIT);
    tf.setColumns(20);
    panel.add(tf);
    try {
      MaskFormatter dateMask = new MaskFormatter("##-##-####");
      dateMask.install(tf);
    } catch (ParseException ex) {
    }

    frame.add(new JButton(), BorderLayout.LINE_START);

    frame.add(panel, BorderLayout.LINE_END);
    frame.pack();
    frame.setVisible(true);
  }
}´

edit2: try adding tf.setFocusLostBehavior(JFormattedTextField.COMMIT); see the JavDoc for further reading.

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