[英]Java: How to remove the spaces in a JFormattedTextField?
所以,我有一個JFormattedTextField
讓用戶輸入一個數字。 數字可以是1到99,所以我使用了MaskFormatter("##")
。 但是,由於某種原因,如果我什么也沒輸入,它會在文本字段中放置2個空格。 這很煩人,因為如果用戶點擊文本字段的中心輸入數字,它會將光標放在2個空格的末尾(因為空格比數字短),因此他們必須返回放置數字。
如何刪除這些空格並保持textfield
空? 我試着做setText("")
但它沒有做任何事情。
這是代碼:
private JFormattedTextField sequenceJTF = new JFormattedTextField();
private JLabel sequenceLabel = new JLabel("Enter a number :");
public Window(){
this.setTitle("Generic title");
this.setSize(350, 250);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
JPanel container = new JPanel();
DefaultFormatter format = new DefaultFormatter();
format.setOverwriteMode(false); //prevents clearing the field if user enters wrong input (happens if they enter a single digit)
sequenceJTF = new JFormattedTextField(format);
try {
MaskFormatter mf = new MaskFormatter("##");
mf.install(sequenceJTF); //assign the maskformatter to the text field
} catch (ParseException e) {}
sequenceJTF.setPreferredSize(new Dimension(20,20));
container.add(sequenceLabel);
container.add(sequenceJTF);
this.setContentPane(container);
}
你的mf.install(sequenceJTF);
下有java核心中的下一個代碼mf.install(sequenceJTF);
:
...
ftf.setText(valueToString(ftf.getValue())); // ftf - JFormattedTextField
...
其中valueToString()
如果沒有字符則返回兩個空格,用於匹配掩碼"##"
。 空格取自MaskFormatter.getPlaceholderCharacter()
,它返回空格作為默認char。
我的解決方案不是那么好,但它有效:
try {
MaskFormatter mf = new MaskFormatter("##") {
@Override
public char getPlaceholderCharacter() {
return '0'; // replaces default space characters with zeros
}
};
mf.install(sequenceJTF); //assign the maskformatter to the text field
} catch (ParseException e) {
e.printStackTrace(); // always, remember, ALWAYS print stack traces
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.