[英]Can someone help me make a JFormattedTextField that works with my code?
I am looking for someone to help me make a JFormattedTextField. 我正在寻找可以帮助我制作JFormattedTextField的人。 I want to to ONLY accept numbers (0-9).
我只想接受数字(0-9)。 When a user inputs a invalid input (EX: "a"), it will not let it be inputted!
当用户输入无效的输入(例如:“ a”)时,将不允许输入! I've tried other pre-made source codes but I don't know where to place it in my code!
我尝试了其他预制的源代码,但是我不知道将其放置在代码中的什么位置! And they always cause errors...
他们总是会导致错误...
Here is my code... 这是我的代码...
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();
}
});
}
As you might see, I already have it set (and imported) to JFormattedTextField. 如您所见,我已经将它设置(并导入)为JFormattedTextField。 But I don't know how to make it actually work.
但是我不知道如何使其真正起作用。 If someone can give me a code that was placed into my code and sent back, that would be great!
如果有人可以给我一个放入我的代码中并发送回去的代码,那就太好了!
Thanks, Maxie_Z :) 谢谢,Maxie_Z :)
For this type of requirements, I'd ditch the JFormattedTextField (you don't want to format but to filter) and use a normal JTextField, with a custom DocumentFilter on its document. 对于这种类型的要求,我放弃了JFormattedTextField(您不想格式化,而是要进行过滤),并使用普通的JTextField,并在其文档上使用自定义DocumentFilter 。 Create a custom filter, and override its
replace
and insertString
methods to only accept digits. 创建一个自定义过滤器,并覆盖其
replace
和insertString
方法以仅接受数字。 You can also beep/change the textfield's background momentarily when a non-digit is entered. 您也可以在输入非数字时立即蜂鸣/更改文本字段的背景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.