[英]Can someone help me make a JFormattedTextField that works with my code?
我正在尋找可以幫助我制作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
方法以僅接受數字。 您也可以在輸入非數字時立即蜂鳴/更改文本字段的背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.