jtextfieldコントロールのポジティブ整数にユーザー入力を制限することは、プログラミングにおいて一般的な問題です。この目的のためにキーリストナーを利用しようとしましたが、より効果的なアプローチがあります。
keylistenerに依存するのではなく、ドキュメントフィルターを実装することは、いくつかの利点を提供します。指定された基準。
PlainDocument doc =(plainDocument)textfield.getDocument(); doc.setDocumentFilter(new intdocumentfilter());
import javax.swing.text.PlainDocument; import javax.swing.text.DocumentFilter; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; class IntDocumentFilter extends PlainDocument { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if (string == null || string.isEmpty()) { super.insertString(fb, offset, string, attr); } else { try { Integer.parseInt(string); super.insertString(fb, offset, string, attr); } catch (NumberFormatException e) { // warn the user and don't allow the insert } } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (text == null || text.isEmpty()) { super.replace(fb, offset, length, text, attrs); } else { try { Integer.parseInt(text); super.replace(fb, offset, length, text, attrs); } catch (NumberFormatException e) { // warn the user and don't allow the insert } } } }
入力文字列を整数として解析できるかどうかを確認します。ユーザーは、nullまたは空の文字列を挿入しようとします。
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3