Java:如何删除JFormattedTextField中的空格?
发布时间:2020-12-15 02:13:07 所属栏目:Java 来源:网络整理
导读:所以,我有一个JFormattedTextField让用户输入一个数字.数字可以是1到99,所以我使用了MaskFormatter(“##”).但是,由于某种原因,如果我什么也没输入,它会在文本字段中放置2个空格.这很烦人,因为如果用户点击文本字段的中心输入数字,它会将光标放在2个空格的末
所以,我有一个JFormattedTextField让用户输入一个数字.数字可以是1到99,所以我使用了MaskFormatter(“##”).但是,由于某种原因,如果我什么也没输入,它会在文本字段中放置2个空格.这很烦人,因为如果用户点击文本字段的中心输入数字,它会将光标放在2个空格的末尾(因为空格比数字短),因此他们必须返回放置数字.
如何删除这些空格并保持文本字段为空?我试着做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核心中有下一个代码:
... 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |