JFormattedTextField :输入持续时间值 [英] JFormattedTextField : input time duration value

查看:47
本文介绍了JFormattedTextField :输入持续时间值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JFormattedTextField 来允许用户将时间 duration 值输入到表单中.示例有效值为:

I want to use a JFormattedTextField to allow the user to input time duration values into a form. Sample valid values are:

2h 30m
72h 15m
6h
0h

但是我在这方面取得的成功有限.有人可以建议如何做到这一点吗?如果使用 JTextField 也可以实现此结果,我就可以了.

However I am having limited success with this. Can some one please suggest how this can be accomplished? I am OK if this result can be achieved using a JTextField as well.

谢谢!

如果值得的话,这是我目前的尝试:

If it is worth anything, here's my current attempt:

 mFormattedText.setFormatterFactory(
    new DefaultFormatterFactory(
        new DateFormatter(
            new SimpleDateFormat("H mm"))));

这有点像:

  • 我无法让 hm 显示为纯文本(我尝试转义) *
  • 小时数有最大值
  • I cannot get h and m to appear as plain text (I tried escaping) *
  • The number of hours has a max

*:见@nanda 的回答

*: See @nanda's answer

推荐答案

代码:

public static void main(String[] args) {
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setLayout(new BorderLayout());
    jFrame.setPreferredSize(new Dimension(500, 500));

    final JFormattedTextField comp = new JFormattedTextField();
    comp.setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(new SimpleDateFormat(
            "H'h' mm'm'"))));
    comp.setValue(Calendar.getInstance().getTime());

    comp.addPropertyChangeListener("value", new PropertyChangeListener() {

        @Override public void propertyChange(PropertyChangeEvent evt) {
            System.out.println(comp.getValue());

        }
    });

    jFrame.getContentPane().add(comp, BorderLayout.CENTER);

    jFrame.pack();
    jFrame.setVisible(true);
}

这篇关于JFormattedTextField :输入持续时间值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆