简体   繁体   English

带有MaskFormatter和DateFormat的JFormattedTextField

[英]JFormattedTextField with MaskFormatter and DateFormat

after reading this article and this question I tried to make a combo of the two: a JFormattedTextField that always shows the slashes in the correct positions and that automatically parses a Date object. 在阅读了本文这个问题之后,我尝试对两者进行组合:一个JFormattedTextField,它总是在正确的位置显示斜杠并自动解析Date对象。

The code I came up with is the following: 我想出的代码如下:

private DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
textField_DaRiassuntoIncassi = new JFormattedTextField(df);
textField_ARiassuntoIncassi = new JFormattedTextField(df);
textField_DaScadenze = new JFormattedTextField(df);
textField_AScadenze = new JFormattedTextField(df);
textField_DaRiassuntoIncassi.setColumns(10);
textField_ARiassuntoIncassi .setColumns(10);
textField_DaScadenze .setColumns(10);
textField_AScadenze .setColumns(10);

try
{
    MaskFormatter dateMask = new MaskFormatter("##/##/####");
    dateMask.install(textField_DaRiassuntoIncassi);
    dateMask.install(textField_ARiassuntoIncassi);
    dateMask.install(textField_DaScadenze);
    dateMask.install(textField_AScadenze);
}
catch(ParseException ex)
{
    ex.printStackTrace();
}

The problem is that when I click on the textfield to input the value, when I type the two slashes are moved as I type, instead I would like them to remain fixed (just like when the key "Insert" on the keyboard is pressed). 问题是,当我单击文本字段输入值时,当我键入时,两个斜杠在我键入时移动,而我希望它们保持固定(就像按下键盘上的“插入”键一样) 。 If I put the MaskFormatter in the constructor that problem goes away, but I can enter any number I want in the textfield, such as "99/00/9874" and the component tells me that's an ok value, because I don't know where to plug the SimpleDateFormat. 如果我把MaskFormatter放在问题消失的构造函数中,但是我可以在文本字段中输入我想要的任何数字,例如“99/00/9874”,组件告诉我这是一个ok值,因为我不知道在哪里插入SimpleDateFormat。

My last resort is to put the MaskFormatter in the JFormattedTextField constructor, get the text with the getText() method, try to parse a date with the DateFormat and in case of error do something, but I think there's a clever way to do this. 我最后的办法是将MaskFormatter放在JFormattedTextField构造函数中,使用getText()方法获取文本,尝试使用DateFormat解析日期,并在出现错误时执行某些操作,但我认为有一种聪明的方法可以做到这一点。 I tried using the method 我尝试过使用这种方法

textField_AScadenze.setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(new SimpleDateFormat("dd/MM/yyyy"))));

but as soon as I don't insert anything and click out the slashes are gone. 但是一旦我没有插入任何东西并且点击了斜线就消失了。 Please help. 请帮忙。 Thank you 谢谢

  • use JSpinner with SpinnerDateModel (out of record, you can to remove two JButtons, but job for very good coder) 使用JSpinner和SpinnerDateModel (记录不足 ,你可以删除两个JButton,但是非常好的编码器工作)

  • for example (would not be going this way, JFormattedTextField could be overkill in some cases) 例如(不会这样,JFormattedTextField在某些情况下可能会过度杀伤)

.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;

public class TimeFormatter extends MaskFormatter {

    private static final long serialVersionUID = 1L;

    public TimeFormatter() { // set mask and placeholder
        try {
            setMask("##/##/####");
            setPlaceholderCharacter('0');
            setAllowsInvalid(false);
            setOverwriteMode(true);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object stringToValue(String string) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        if (string == null) {
            string = "00/00/0000";
        }
        return df.parse(string);
    }

    @Override
    public String valueToString(Object value) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        if (value == null) {
            value = new Date(0);
        }
        return df.format((Date) value);
    }

    private void MyGui() {
        final MaskFormatter formatter = new TimeFormatter(); // textfield 1: create formatter and textfield
        //formatter.setValueClass(java.util.Date.class);
        final JFormattedTextField tf2 = new JFormattedTextField(formatter);// textfield 2: create formatter and textfield
        tf2.setValue(new Date()); // no initial value        
        final JLabel label = new JLabel();
        JButton bt = new JButton("Show Value");// button to show current value
        bt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(" value 2 = " + tf2.getValue());
                System.out.println(" value 2 = " + tf2.getText());
                System.out.println("value class: " + formatter.getValueClass());
                label.setText(tf2.getText());
            }
        });        
        JFrame f = new JFrame(); // main frame
        f.getContentPane().setLayout(new GridLayout());
        f.getContentPane().add(tf2);
        f.getContentPane().add(label);
        f.getContentPane().add(bt);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        Runnable doRun = new Runnable() {
            @Override
            public void run() {
                new TimeFormatter().MyGui();
            }
        };
        SwingUtilities.invokeLater(doRun);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM