2013-10-05 176 views
0

我试图限制多个jtextfield上的字符输入。这两个字段有不同的字符限制,同时他们不能接受空白作为他们的第一个字符...例如第一个字段只有5个字符的限制,然后第二个字段有10char限制..我被困在这个问题上这里是我使用的代码:在jtextfield或区域限制字符输入

import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
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 Restriction { 

    public Restriction() { 
     initComponents(); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new Restriction(); 
      } 
     }); 
    } 

    private void initComponents() { 
     GridBagConstraints Cons = new GridBagConstraints(); 
     JFrame frame = new JFrame(); 
     JPanel panel = new JPanel(new GridBagLayout()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JTextField jtf = new JTextField(20); 
     JTextField jtf2 = new JTextField(20); 
     //add filter to document 
     ((AbstractDocument) jtf.getDocument()).setDocumentFilter(new MyDocumentFilter()); 
     MyDocumentFilter.charLimit(5); 
     ((AbstractDocument) jtf2.getDocument()).setDocumentFilter(new MyDocumentFilter()); 
     MyDocumentFilter.charLimit(10); 
     Cons.gridy = 0; 
     panel.add(jtf, Cons); 
     Cons.gridy = 1; 
     panel.add(jtf2,Cons); 
     frame.add(panel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

class MyDocumentFilter extends DocumentFilter { 

    static int Limit; 

    public static void charLimit(int Limitation){ 
     Limit = Limitation; 
    } 

    @Override 
    public void replace(FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException { 
     //we want standard behavior if we are not placing space at start of JTextField 
     //or if we are placing text at start of JTextField but first character is not whitespace 
     if (i!=0 && i< Limit || (i==0 && !Character.isWhitespace(string.charAt(0)))){ 
      super.replace(fb, i, i1, string, as); 
     }else{ 
      System.out.println("no spaces allowed"); 
     } 
    } 

    @Override 
    public void remove(FilterBypass fb, int i, int i1) throws BadLocationException { 
     super.remove(fb, i, i1); 
    } 

    @Override 
    public void insertString(FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException { 
     super.insertString(fb, i, string, as); 

    } 
} 

回答

0

我会用javax.swing.text.Document

可以启动它想:

public static Document createTextDocument(int maxLength){ 
     return new TextDocument(maxLength); 
    } 

... 

Document document = createTextDocument(5); // limit to 5 chars 
textField1.setDocument(document); 

document = createTextDocument(10); // limit to 10 chars 
textField2.setDocument(document); 

这是自TextDocument类:

public class TextDocument extends PlainDocument{ 


    private static final long serialVersionUID = 1L; 
    private int maxLength = Integer.MAX_VALUE; 

    TextDocument(){} 
    TextDocument(int maxlength){this.maxLength=maxlength;} 

    public void setMaxLength(int maxLength) { 
      if (maxLength < 0) 
       throw new IllegalArgumentException("maxLength<0"); 
      this.maxLength = maxLength; 
     } 

    public void insertString(int offset, String str, AttributeSet attr) 
    throws BadLocationException { 
     if (validateLength(offset, str) == false) 
       return; 

      super.insertString(offset, str, attr); 
    } 

    private boolean validateLength(int offset, String toAdd) { 
      String str_temp; 
      //String str_text = ""; 
      String str1 = ""; 
      String str2 = ""; 
      try { 
       str1 = getText(0, offset); 
       str2 = getText(offset, getLength() - offset); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      str_temp = str1 + toAdd + str2; 
      if (maxLength < str_temp.length()) { 
       beep(); 
       return false; 
      } else 
       return true; 

     } 

     private void beep() { 
      java.awt.Toolkit.getDefaultToolkit().beep(); 
     } 
} 

希望这将有助于

+0

感谢您的答复..但我的问题仍然存在,我试图限制2 JTextField中具有不同的字符限制,但同时它不接受空格作为它的第一个字符 – Criz

+0

看我的例子,你用'TextDocument '刚开始时只提供关于空白空间的5和10 –

+0

,只需在'validateLength'方法中改变我的类。非常简单 –

0

你能避免使用文档通过重写每个JTextField中的keyTyped事件的复杂性:

txtGuess = new JTextField(); 
txtGuess.addKeyListener(new KeyAdapter() { 
    public void keyTyped(KeyEvent e) { 
     if (txtGuess.getText().length() >= 3) // limit textfield to 3 characters 
      e.consume(); 
    } 
}); 

这限制了一个猜谜游戏文本字段中的字符数通过覆盖keyTyped事件并检查文本字段是否已经有3个字符 - 如果是这样,您正在“消费”关键事件(e),以便它不像正常那样得到处理。

希望它的帮助。