ユーザーに 12:00 のように時刻を入力してもらいたいのですが、いくつかのことを把握する必要があり、道に迷ってしまいます。
- テキストを 5 文字に制限することはできますか?
- ユーザーが削除できないように、コードにコロンを埋め込むことはできますか?
- 最後に、そのコードを取得して、それが数字だけであることを確認できますか (もちろんコロンは無視します)
ユーザーに 12:00 のように時刻を入力してもらいたいのですが、いくつかのことを把握する必要があり、道に迷ってしまいます。
答えは、JFormattedTextFieldとMaskFormatterを使用することです。
例えば:
String mask = "##:##";
MaskFormatter timeFormatter = new MaskFormatter(mask);
JFormattedTextField formattedField = new JFormattedTextField(timeFormatter);
Javaコンパイラでは、MaskFormatterを作成するときにParseExceptionをキャッチまたはスローする必要があるため、必ずこれを実行してください。
または、テキストフィールドを捨てて、コロンを含むことでJSpinner
区切られた2つのインスタンス(または2つのインスタンス)を選択します。JLabel
JTextField
このソリューションがユーザーにとってより直感的であるかどうかは完全にはわかりませんが、そう思います。
古い質問への遅い回答。を使用するとDocumentFilter
、その 3 つの要件を達成できます。
非生産品質のコードは次のようになります
String TIME_PATTERN = "^\\d\\d:\\d\\d\\s[AP]M$";
final JTextField tf = new JTextField("00:00 AM", 8);
((AbstractDocument)tf.getDocument()).setDocumentFilter(new DocumentFilter() {
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength());
text = text.substring(0, offs) + str + text.substring(offs + length);
if(text.matches(TIME_PATTERN)) {
super.replace(fb, offs, length, str, a);
return;
}
text = fb.getDocument().getText(0, fb.getDocument().getLength());
if(offs == 2 || offs == 5)
tf.setCaretPosition(++offs);
if(length == 0 && (offs == 0 ||offs == 1 ||offs == 3 ||offs == 4 ||offs == 6))
length = 1;
text = text.substring(0, offs) + str + text.substring(offs + length);
if(!text.matches(TIME_PATTERN))
return;
super.replace(fb, offs, length, str, a);
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { }
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { }
});