如何限制 JTextField 的字符数

发布于 2024-11-10 03:19:00 字数 1075 浏览 4 评论 0原文

我必须限制 JTextField 中的字符数。我使用以下代码来执行此操作,但问题是我使用虚拟键盘将数据输入到 JTextField。所以偏移量始终设置为0。当我输入超过指定数量的字符时,它会重置该字段并从头开始执行。例如,如果我的限制是 3 个字符,并且我输入 xyz0,我的有限文本框将读取最多 z 的字符,然后清除该字段并再次重新启动。所以我在字段中留下了 0 。代码如下。

  public class JTextFieldLimit extends PlainDocument {
  private int limit;  
  public JTextFieldLimit(int limit) {  
   super();  
   this.limit = limit;  
   }  
    @Override  
  public void insertString( int offset, String  str, AttributeSet attr ) throws   BadLocationException {  
    if (str == null) return;  
            System.out.println("from document helper getLength():"+getLength());  
            System.out.println("from document helper str.length():"+str.length());  
            System.out.println("from document helper str:"+str);  
            System.out.println("from document helper attr:"+attr);  
            System.out.println("from document helper offset:"+offset);  
    if ((getLength() + str.length()) <= limit) {  
      super.insertString(offset, str, attr);  
    }  
  }  
}  

I have to restrict the number of characters in the JTextField. I used the following code to do that but the problem is i am feeding the data to JTextField using the virtual keyboard. So the offset is set to 0 all the time. When i enter more than the specified number of characters it resets the field and start doing it from the beginning. For example if my limit is 3 characters and i am entering xyz0 my limited textbox reads the character upto z and then clears the field and restart again. So i am left with 0 in the field. The code is as follows.

  public class JTextFieldLimit extends PlainDocument {
  private int limit;  
  public JTextFieldLimit(int limit) {  
   super();  
   this.limit = limit;  
   }  
    @Override  
  public void insertString( int offset, String  str, AttributeSet attr ) throws   BadLocationException {  
    if (str == null) return;  
            System.out.println("from document helper getLength():"+getLength());  
            System.out.println("from document helper str.length():"+str.length());  
            System.out.println("from document helper str:"+str);  
            System.out.println("from document helper attr:"+attr);  
            System.out.println("from document helper offset:"+offset);  
    if ((getLength() + str.length()) <= limit) {  
      super.insertString(offset, str, attr);  
    }  
  }  
}  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原谅我要高飞 2024-11-17 03:19:01

您应该按照本教程使用 DocumentFilter。例如:

import javax.swing.*;
import javax.swing.text.*;

public class JTextFieldLimit2 extends JPanel{
   JTextField textfield = new JTextField(5);

   public JTextFieldLimit2() {
      PlainDocument doc = (PlainDocument) textfield.getDocument();
      doc.setDocumentFilter(new TextLengthDocFilter(3));

      add(textfield);
   }

   private class TextLengthDocFilter extends DocumentFilter {
      private int maxTextLength;

      public TextLengthDocFilter(int maxTextLength) {
         this.maxTextLength = maxTextLength;
      }

      private boolean verifyText(String text) {
         return text.length() <= maxTextLength;
      }

      @Override
      public void insertString(FilterBypass fb, int offset, String string,
               AttributeSet attr) throws BadLocationException {

         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);
         sb.insert(offset, string);

         if (verifyText(sb.toString())) {
            super.insertString(fb, offset, string, attr);
         }

      }

      @Override
      public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
               throws BadLocationException {
         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);

         sb.replace(offset, offset + length, text);
         if (verifyText(sb.toString())) {
            super.replace(fb, offset, length, text, attrs);
         }
      }

      @Override
      public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);

         sb.replace(offset, offset + length, "");

         if (verifyText(sb.toString())) {
            super.remove(fb, offset, length);            
         }
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("JTextFieldLimit2");
      frame.getContentPane().add(new JTextFieldLimit2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

You should use a DocumentFilter as per this tutorial. For example:

import javax.swing.*;
import javax.swing.text.*;

public class JTextFieldLimit2 extends JPanel{
   JTextField textfield = new JTextField(5);

   public JTextFieldLimit2() {
      PlainDocument doc = (PlainDocument) textfield.getDocument();
      doc.setDocumentFilter(new TextLengthDocFilter(3));

      add(textfield);
   }

   private class TextLengthDocFilter extends DocumentFilter {
      private int maxTextLength;

      public TextLengthDocFilter(int maxTextLength) {
         this.maxTextLength = maxTextLength;
      }

      private boolean verifyText(String text) {
         return text.length() <= maxTextLength;
      }

      @Override
      public void insertString(FilterBypass fb, int offset, String string,
               AttributeSet attr) throws BadLocationException {

         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);
         sb.insert(offset, string);

         if (verifyText(sb.toString())) {
            super.insertString(fb, offset, string, attr);
         }

      }

      @Override
      public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
               throws BadLocationException {
         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);

         sb.replace(offset, offset + length, text);
         if (verifyText(sb.toString())) {
            super.replace(fb, offset, length, text, attrs);
         }
      }

      @Override
      public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
         Document doc = fb.getDocument();
         String oldText = doc.getText(0, doc.getLength());
         StringBuilder sb = new StringBuilder(oldText);

         sb.replace(offset, offset + length, "");

         if (verifyText(sb.toString())) {
            super.remove(fb, offset, length);            
         }
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("JTextFieldLimit2");
      frame.getContentPane().add(new JTextFieldLimit2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文