限制用户在 JTextField 中输入时间的最佳方法 [英] Best way to constrain user to enter a time in a JTextField
问题描述
在我的一个 Java 应用程序中,有一个 字段,用户应该在其中输入时间.我知道,我可以简单地将它保留为普通的 JTextField
并且在验证时我可以检查值等等......
In one of my java applications, there is a field where the user is supposed to enter a time. I know, I can simply keep it as a normal JTextField
and at the time of validation I can check the value and so on...
但我认为有比这更好的方法..
But I think there is a better way than that..
比如这是一个带日期的事情,那么JXDatePicker
(swingx
自带的)就可以很方便的使用了.最终,用户选择被保证是一个日期.
For example, if this is a matter with a date, then JXDatePicker
(which comes with swingx
) can be used very handily. Eventually, the users selection is guaranteed to be a date.
同样,也必须有更好的时间选择方法.如果您知道更好的解决方案,有人会分享您的知识吗?
Likewise, there must be a better way for time selection too. Will someone share your knowledge if you know a better solution.
任何想法都值得赞赏.谢谢!
Any thought is appreciated. Thank you!
推荐答案
you can use a JFormattedTextField
看看下面的例子,这将创建一个 JFormattedTextField
将只接受数字并将它们放在 XXhXXminXXs 的形式中,然后将 ActionListener
添加到 JFormattedTextField
并尝试解析为有效的时间对象当 ENTER 现在我只展示了 JFormattedTextField
和 ActionListener
的使用我没有尝试转换或任何转换和解析为有效时间:
you could use a JFormattedTextField
have a look at the example below, this will create a JFormattedTextField
which will accept only numbers and put them in the form XXhXXminXXs then add a ActionListener
to the JFormattedTextField
and in that attempt to parse to a valid time object when ENTER for now I only show the use of the JFormattedTextField
and the ActionListener
I didn't attempt to convert or any converting and parsing for valid time:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;
public class FormattedTextFieldExample {
public FormattedTextFieldExample() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("JFormattedTextField Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##h##min##s");//the # is for numeric values
mask.setPlaceholderCharacter('#');
} catch (ParseException e) {
e.printStackTrace();
}
//
// Create a formatted text field that accept a valid time.
//
final JFormattedTextField timeField = new JFormattedTextField(mask);
//Add ActionListener for when enter is pressed
timeField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == timeField) {
//parse to a valid time here
System.out.println(timeField.getText());
}
}
});
frame.add(timeField);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new FormattedTextFieldExample();
}
});
}
}
这篇关于限制用户在 JTextField 中输入时间的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!