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

查看:159
本文介绍了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"))));

除了:


  • 我无法将 h m 显示为纯文本(我试过了)逃避) *

  • 小时数最多

  • 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天全站免登陆