简体   繁体   English

Java:如何删除JFormattedTextField中的空格?

[英]Java: How to remove the spaces in a JFormattedTextField?

So, I've got a JFormattedTextField to let the user enter a number. 所以,我有一个JFormattedTextField让用户输入一个数字。 The number can be from 1 to 99, so I used a MaskFormatter("##") . 数字可以是1到99,所以我使用了MaskFormatter("##") However, for some reason it puts 2 spaces in the text field if I enter nothing. 但是,由于某种原因,如果我什么也没输入,它会在文本字段中放置2个空格。 It's annoying because if the user clicks in the center of the text field to enter the numbers, it puts the cursor at the end of the 2 spaces (because spaces are shorter than numbers) and so they have to go back to put the number. 这很烦人,因为如果用户点击文本字段的中心输入数字,它会将光标放在2个空格的末尾(因为空格比数字短),因此他们必须返回放置数字。

How do I remove those spaces and keep the textfield empty? 如何删除这些空格并保持textfield空? I tried to do setText("") but it doesn't do anything. 我试着做setText("")但它没有做任何事情。

Here's the code: 这是代码:

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);
  }

There is the next code in java core under yours mf.install(sequenceJTF); 你的mf.install(sequenceJTF);下有java核心中的下一个代码mf.install(sequenceJTF); :

...
ftf.setText(valueToString(ftf.getValue())); // ftf - JFormattedTextField
...

where valueToString() returns two spaces if there is no characters, for matching the mask "##" . 其中valueToString()如果没有字符则返回两个空格,用于匹配掩码"##" Spaces are taken from MaskFormatter.getPlaceholderCharacter() which returns space as default char. 空格取自MaskFormatter.getPlaceholderCharacter() ,它返回空格作为默认char。

My solution is not so good, but it works: 我的解决方案不是那么好,但它有效:

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.

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