带有初始值的JFormattedTextField,可以逐个符号覆盖

时间:2014-06-18 08:09:05

标签: java swing date formatter jformattedtextfield

我有这么简单的代码创建了JFormattedTextField,它应该包含一个出生日期(只有数字除以连字符):

MaskFormatter mf = new MaskFormatter("##-##-####");
mf.setPlaceholderCharacter('_');
JFormattedTextField birthDate = new JFormattedTextField(mf);

但是如何创建birthDate以便它包含初始值“dd-mm-yyyy”。
我知道有setPlaceholder("some string")之类的东西,但是当我使用它时,只有改变birthDate的walue的方法是选择整个存在的内容,然后键入新的内容。
我的目的是允许用户按标志覆盖现有内容,如果失去焦点后不允许这个值,则返回初始值。例如。

  

1d-mm-yyyy
11-mm-yyyy
11-0m-yyyy(现在出生日期正在失去   焦点)
dd-mm-yyyy(因为价值是错误的,诞生日期是如此   开始)

JFormattedTextField的这种行为是否可能?或者可能有更合适的JComponent吗?

1 个答案:

答案 0 :(得分:2)

使用JCalendar的一些方法

不仅仅是方向的答案

JSpinner的简单代码示例(我不能找到PropertyChangeListener / Support的通知程序)

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class TimeZoneSpinners {

    private final String[] zones = {"Asia/Tokyo", "Asia/Hong_Kong",
        "Asia/Calcutta", "Europe/Paris", "Europe/London",
        "America/New_York", "America/Los_Angeles"
    };
    private final JLabel[] labels = new JLabel[zones.length];
    private final SimpleDateFormat[] formats = new SimpleDateFormat[zones.length];
    private JSpinner spinner;
    private SpinnerDateModel model;
    private SimpleDateFormat format;
    private JPanel panel;
    private JFrame frame = new JFrame();

    public TimeZoneSpinners() {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        model = new SpinnerDateModel();
        model.setValue(date);
        spinner = new JSpinner(model);
        spinner.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                Date date = (Date) ((JSpinner) e.getSource()).getValue();
                for (int i = 0; i < labels.length; i++) {
                    labels[i].setText(formats[i].format(date));
                }
            }
        });
        format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
        format.setTimeZone(TimeZone.getTimeZone(zones[0]));
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        format.applyPattern("HH:mm:ss");
        panel = new JPanel(new GridLayout(zones.length, 2, 10, 10));
        for (int i = 0; i < zones.length; i++) {
            formats[i] = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
            formats[i] = new SimpleDateFormat("HH:mm:ss");
            formats[i].setTimeZone(TimeZone.getTimeZone(zones[i]));
            JLabel label = new JLabel(zones[i]);
            labels[i] = new JLabel(formats[i].format(date));
            labels[i].setHorizontalAlignment(JLabel.RIGHT);
            panel.add(label);
            panel.add(labels[i]);
        }
        frame.setLayout(new BorderLayout(10, 10));
        frame.add(spinner, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TimeZoneSpinners();
            }
        });
    }
}

你应该能够覆盖AbstractFormatter/InternationalFormatter (example for number instance only)或覆盖JFormattedTextField / JSpinner的那些方法,并使用输入大小和验证器,例如。

import javax.swing.*;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.InternationalFormatter;
import java.text.DateFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateSpinner extends JSpinner {

    private static final long serialVersionUID = 1L;
    public DefaultFormatter _formatter;
    public DateEditor _timeEditor;
    public DateFormat _format;

    public DateSpinner() {
        this("hh:mm:ss");
    }

    public DateSpinner(String format) {
        this(format, new Date());
    }

    public DateSpinner(String format, Date date) {
        super(new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY));
        setFormat(format);
        customizeSpinner();
    }

    private void customizeDateEditor() {
        JFormattedTextField.AbstractFormatter formatter = _timeEditor.getTextField().getFormatter();
        if (formatter instanceof DefaultFormatter) {
            _formatter = (DefaultFormatter) formatter;
        } else {
            throw new IllegalStateException("The formatter is not an instance of DefaultFormatter.");
        }
        if (formatter instanceof InternationalFormatter) {
            Format f = ((InternationalFormatter) formatter).getFormat();
            if (f instanceof DateFormat) {
                _format = ((DateFormat) f);
            }
        }
        if (_format == null) {
            throw new IllegalStateException("The format is not an instance of SimpleDateFormat.");
        }
    }

    private void setFormat(String format) {
        _timeEditor = createDateEditor(format);
        customizeDateEditor();
        setEditor(_timeEditor);
    }

    private void customizeSpinner() {
        setLenient(false);
        setCommitsOnValidEdit(true);
        setAllowsInvalid(false);
        setOverwriteMode(true);
    }

    protected DateEditor createDateEditor(String format) {
        return new DateEditor(this, format);
    }

    public void setCommitsOnValidEdit(boolean commit) {
        _formatter.setCommitsOnValidEdit(commit);
    }

    public boolean getCommitsOnValidEdit() {
        return _formatter.getCommitsOnValidEdit();
    }

    public void setOverwriteMode(boolean overwriteMode) {
        _formatter.setOverwriteMode(overwriteMode);
    }

    public boolean getOverwriteMode() {
        return _formatter.getOverwriteMode();
    }

    public void setAllowsInvalid(boolean allowsInvalid) {
        _formatter.setAllowsInvalid(allowsInvalid);
    }

    public boolean getAllowsInvalid() {
        return _formatter.getAllowsInvalid();
    }

    public void setTimeZone(TimeZone zone) {
        _format.setTimeZone(zone);
    }

    public TimeZone getTimeZone() {
        return _format.getTimeZone();
    }

    public void setLenient(boolean lenient) {
        _format.setLenient(lenient);
    }

    public boolean isLenient() {
        return _format.isLenient();
    }
}