0

私がやりたいのは、TextField内に何かを入力するときに、記号を許可しないようにすることです。シンボルを除外する方法は?

私が使用したコード:

 if (evt.getKeyChar()=='&'||evt.getKeyChar()=='@') {
       jTextField2.setText("");
    }
4

2 に答える 2

6

DocumentFilterを使用する必要があります。これは非常に単純で基本的なデモの例です。

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestDocumentFilter {

    private void initUI() {
        JFrame frame = new JFrame(TestDocumentFilter.class.getSimpleName());
        frame.setLayout(new FlowLayout());
        final JTextField textfield = new JTextField(20);
        ((AbstractDocument) textfield.getDocument()).setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                string = string.replace("&", "").replace("@", "");
                super.insertString(fb, offset, string, attr);
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                text = text.replace("&", "").replace("@", "");
                super.replace(fb, offset, length, text, attrs);
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textfield);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                new TestDocumentFilter().initUI();
            }
        });
    }

}
于 2012-11-16T08:06:39.607 に答える
2

JFormattedTextField

JTextField に 1 つではなく 2 つのプロパティがあります。

(1) 文字列 "text" が表示され、(2) 任意のクラス "value" が表示されます

必要なのは、stringToValue() と valueToString() を変換するフォーマッターを配置することだけです。

import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.JTextComponent;

...

  DefaultFormatter formatter = new DefaultFormatter() {
    {
      setValueClass(String.class); // property "value" of String.class
      setAllowsInvalid(false); // doesnt matter in current example, but very usefull
      setCommitsOnValidEdit(true); // convert value back to text after every valid edit
    }
    @Override
    public Object stringToValue(String string) throws ParseException {
      string = string.replace("&","").replace("@","");
      return string;
    }
  };

  JTextComponent txt = new JFormattedTextField(formatter);

さらに、できる

  txt.addPropertyChangeListener("value", yourPropertyChangeListener);

変更後すぐに値を取得する

于 2012-11-16T09:26:17.443 に答える