java - 有人可以帮我制作一个适用于我的代码的 JFormattedTextField 吗?

标签 java numbers jframe jtextfield jformattedtextfield

我正在找人帮我制作 JFormattedTextField。我只想接受数字(0-9)。当用户输入无效的输入(例如:“a”)时,它不会让其输入!我尝试过其他预制源代码,但我不知道将其放在我的代码中的哪里!而且它们总是会导致错误......

这是我的代码...

private void followerPrompt() {
    JFormattedTextField followerPrompt=new JFormattedTextField("0");  
    JFrame followerPromptWindow=new JFrame("Enter the number of followers you have:");  
    followerPromptWindow.setLayout(new GridLayout(2,1,1,1));  
    followerPromptWindow.add(followerPrompt);
    followerPromptWindow.setResizable(false);
    followerPromptWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    followerPromptWindow.setLocation(500, 400);
    followerPromptWindow.setVisible(true);  
    followerPromptWindow.setSize(promptWindowWidth * promptWindowScale,promptWindowHeight * promptWindowScale);  
    JButton followerPromptWindowButton = new JButton("Next Step");
    followerPromptWindow.add(followerPromptWindowButton);
    followerPromptWindowButton.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e) {         
            followerInput = followerPrompt.getText();
            System.out.println("Follower Input: " + followerInput);
            likePrompt();
            followerPromptWindow.dispose();
        }
    });
}

正如您所见,我已经将其设置(并导入)到 JFormattedTextField。但我不知道如何让它真正发挥作用。如果有人能给我一个代码,将其放入我的代码中并发回,那就太好了!

谢谢, 马克西_Z:)

最佳答案

对于这种类型的要求,我会放弃 JFormattedTextField (您不想格式化而是要过滤)并使用普通的 JTextField 和自定义 DocumentFilter在其文件上。创建一个自定义过滤器,并重写其 replaceinsertString 方法以仅接受数字。当输入非数字时,您还可以立即发出蜂鸣声/更改文本字段的背景。

关于java - 有人可以帮我制作一个适用于我的代码的 JFormattedTextField 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29260325/

相关文章:

java - 使用 PagedResources/嵌入对象反序列化日期。 jackson . Spring

java - 如何将字符串数字格式化为逗号和四舍五入?

java - 将菜单栏添加到 JFrame

java - 尝试在 Swing worker 体内绘制矩形

java - 将 MVC 模型与 Swing 应用程序框架结合使用

java - Kafka 流到主题

ios - 最小正浮点值是多少?

javascript - toBeCloseTo 等效于 Jest 中的递归相等性测试

java - JFrame 中的渐变背景

Java 数组 - 搜索数组中的元素,然后找到索引