我正在寻找可以帮助我制作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。但是我不知道如何使其真正起作用。如果有人可以给我一个放入我的代码中并发送回去的代码,那就太好了!
谢谢,Maxie_Z :)
对于这种类型的要求,我放弃了JFormattedTextField(您不想格式化,而是要进行过滤),并使用普通的JTextField,并在其文档上使用自定义DocumentFilter。创建一个自定义过滤器,并覆盖其replace
和insertString
方法以仅接受数字。您也可以在输入非数字时立即蜂鸣/更改文本字段的背景。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句