我正在寻找帮助我制作JFormattedTextField的人。我想只接受数字(0-9)。当用户输入无效输入时(EX:" 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。但我不知道如何让它真正起作用。如果有人可以给我一个放在我的代码中并发回的代码,那就太好了!
谢谢, Maxie_Z:)
答案 0 :(得分:1)
对于这种类型的要求,我放弃了JFormattedTextField(您不想格式化但要过滤)并使用普通的JTextField,并在其文档中使用自定义DocumentFilter。创建自定义过滤器,并覆盖其replace
和insertString
方法以仅接受数字。输入非数字时,您也可以短暂地发出/更改文本字段的背景。