有人可以帮我制作一个适用于我的代码的 JFormattedTextField 吗?
Can someone help me make a JFormattedTextField that works with my code?
我正在寻找帮助我制作 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:)
对于这种类型的要求,我会放弃 JFormattedTextField(您不想格式化而是要过滤)并使用普通的 JTextField,在其文档上带有自定义 DocumentFilter。创建自定义过滤器,并覆盖其 replace
和 insertString
方法以仅接受数字。当输入非数字时,您还可以 beep/change 文本字段的背景。
我正在寻找帮助我制作 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:)
对于这种类型的要求,我会放弃 JFormattedTextField(您不想格式化而是要过滤)并使用普通的 JTextField,在其文档上带有自定义 DocumentFilter。创建自定义过滤器,并覆盖其 replace
和 insertString
方法以仅接受数字。当输入非数字时,您还可以 beep/change 文本字段的背景。