简体   繁体   中英

Can someone help me make a JFormattedTextField that works with my code?

I am looking for someone to help me make a JFormattedTextField. I want to to ONLY accept numbers (0-9). When a user inputs a invalid input (EX: "a"), it will not let it be inputted! 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. 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 :)

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. Create a custom filter, and override its replace and insertString methods to only accept digits. You can also beep/change the textfield's background momentarily when a non-digit is entered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM