0

我有一个“格式化”字段——也就是说,它最终必须是这样的形式:xx/xxxx/xx 我想这样做,以便在键入时自动添加“/”。

我试图拼凑的方式是这样的:

JTextField field = new JTextField ("xx/xxxx/xx");

// a focus listener to clear the "xx/xxxx/xx" on focus & restore on focus-out
// the override the 'document' with this:
field.setDocument (new PlainDocument () {
    public void insertString (int off, String str, AttributeSet attr) throws BadLocationException {
      if (off == 2 || off == 7) {
        super.insertString (off + 1, str + "/", attr);
      }
    }
}

这似乎要崩溃了——当它从 xx/xx.. 到 xx 时,我该如何正确处理?我认为让他们删除“/”是可以的。

我觉得应该有更好的方法?也许我可以使用一个图书馆?除了我的……特别的东西。

感谢您的任何输入!

4

2 回答 2

3

嗯,你可以JFormattedTextField看看下面的例子,这将创建一个JFormattedTextField只接受数字并将它们以 XX/XXXX/XX 的形式放置:

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;

public class FormattedTextFieldExample extends JFrame {

    public FormattedTextFieldExample() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(new Dimension(200, 200));
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        MaskFormatter mask = null;
        try {
            //
            // Create a MaskFormatter for accepting phone number, the # symbol accept
            // only a number. We can also set the empty value with a place holder
            // character.
            //
            mask = new MaskFormatter("##/####/##");
            mask.setPlaceholderCharacter('_');
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //
        // Create a formatted text field that accept a valid phone number.
        //
        JFormattedTextField phoneField = new JFormattedTextField(mask);
        phoneField.setPreferredSize(new Dimension(100, 20));
        getContentPane().add(phoneField);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new FormattedTextFieldExample().setVisible(true);
            }
        });
    }
}

参考:

于 2012-08-06T06:27:42.260 回答
0

为了实现这一点,我这样做了:

JTextField field = new JTextField ();

field.setDocument (new PlainDocument () {
  public void insertString (int off, String str, AttributeSet attr) throws BadLocationException {
    if (off < 10) {  // max size clause
      if (off == 1 || off == 6) { // insert the '/' occasionally
        str = str + "/";
      }
      super.insertString (off, str, attr);
    }
  }
});

field.setText ("xx/xxxx/xx"); // set AFTER otherwise default won't show up!
field.setForeground (ColorConstants.DARK_GRAY_080); // make it light! 
field.addFocusListener (new ClearingFocusListener (field)); // could be done in an anonymous inner class - but I use it other places

private static class ClearingFocusListener implements FocusListener {
  final private String initialText;
  final private JTextField field;

  public ClearingFocusListener (final JTextField field) {
    this.initialText = field.getText ();
    this.field = field;
  }

  @Override
  public void focusGained (FocusEvent e) {
    if (initialText.equals (field.getText ())) {
      field.setText ("");
      field.setForeground (ColorConstants.DARK_GRAY_080);
    }
  }

  @Override
  public void focusLost (FocusEvent e) {
    if ("".equals (field.getText ())) {
      field.setText (initialText);
      field.setForeground (ColorConstants.LIGHT_GRAY_220);
    }
  }
}

这与其他解决方案的不同之处在于,当没有文本时,'/' 不存在,它被添加到正确的位置。它目前不处理任何替换的东西——嗯。:/

于 2012-08-06T07:49:36.787 回答