gpt4 book ai didi

java - JFormattedTextField 具体格式

转载 作者:搜寻专家 更新时间:2023-11-01 03:23:55 24 4
gpt4 key购买 nike

我需要按照“00:00”格式制作一个 JFormattedTextField 并满足一些要求:

  • 唯一可变的应该是“00”之一。 (所以“:”不应该被删除)
  • Tab 使您可以在“:”的两侧之间切换。 (因此,将光标放在一侧并使用制表符在另一侧标记“00”)
  • 将“00”更改为“2”应将其格式化为“02”。
  • 它的字符限制应为 5,包括“:”。 (4 个可变字符)
  • 它应该被初始化为“00:00”,但它不应该是一个可接受的输入。
  • 您不能输入数字以外的任何内容。 (字母、符号、负数等)

有没有办法做到这一点?我查看了不同的格式化程序、验证程序和文档过滤器以添加到 JFormattedTextField,但我不确定要使用哪些。 (现在使用 DefaultFormatter,但已经查看了 NumberFormatter 的限制。我需要使用格式化程序和验证程序的组合吗?)

这是我现在的 JFormattedTextField:http://pastebin.com/jW2RSJXe[1]。

从执行此操作的代码到有关外观的示例/指针的任何内容都将不胜感激!

最佳答案

运行这个例子。它使用 MaskFormatter: 永久存在,但我不确定如何格式化你问题的另一部分,如果你只有 2 个,它将显示 02。你可以玩弄它

import java.awt.BorderLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class MaskFormatterTest extends JPanel {

private JFormattedTextField formatText;

public MaskFormatterTest() {
formatText = new JFormattedTextField(createFormatter("##:##"));
formatText.setColumns(20);
formatText.setText("00:00");

setLayout(new BorderLayout());
add(new JLabel("Enter only numbers"), BorderLayout.NORTH);
add(formatText, BorderLayout.CENTER);
}

private MaskFormatter createFormatter(String s) {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(s);
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return formatter;
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("MaskFormatter example");
frame.add(new MaskFormatterTest());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
});
}
}

MaskFormatter 设置每个字符在每个位置的类型值和允许的大小。在本例中,我使用了 ##:##。允许两位数字、一个冒号和另外两位数字。

更新: 添加了 formatText.setText("00:00"); 代码来初始化文本字段。

关于java - JFormattedTextField 具体格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20581159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com