2012-08-27 36 views
0

所以,我有一个JTextAreaJTextArea行限制

我需要它的设置方式,它可以防止用户输入超过4行的文本。 我找到了一种计算线条的方法。 但是也必须考虑复制/粘贴。而且我不使用等宽字体。

有没有办法做到这一点考虑到了这一切?

+0

尝试此链接:

回答

3

为什么不加DocumentListener和检查线每次文本被删除,插入或改变了JTextArea量:

JTextArea.getDocument().addDocumentListener(new DocumentListener() { 
    public void changedUpdate(DocumentEvent e) { 
    check(); 
    } 
    public void removeUpdate(DocumentEvent e) { 
    check(); 
    } 
    public void insertUpdate(DocumentEvent e) { 
    check(); 
    } 

    public void check() { 
    if (JTextArea.getLineCount()>4){//make sure no more than 4 lines 
     JOptionPane.showMessageDialog(null, "Error: Cant have more than 4 lines", JOptionPane.ERROR_MESSAGE); 
    } 
    } 
}); 
+0

是否有可能在的DocumentEvent访问的JTextArea è? – Karlovsky120

+0

@ Karlovsky120你的意思是什么? –

+0

JTextArea是我的程序中的一个类。我无法在其内部引用该类,因此我必须以某种方式将它作为DocumentEvent的源代码来访问......这可能吗? – Karlovsky120

0

您需要定义一个关键的监听器和内部的肯定,我们需要定义下一个代码是我的解决方案,我希望它有帮助。

//// 
textfield.addKeyListener(new KeyListener() { 
       public void keyPressed(KeyEvent e) { 
        // TODO Auto-generated method stub 
        if(textfield.getLineCount() == maximum_number_of_your_default) { 
         c = ta.getCaret(); 
    // c is an object of Caret class as : Caret c; initialization only. 
         a = c.getDot(); 
    // a is an integer value initialized by zero as : int a = 0; 
        } 
        if(ta.getLineCount() > maximum_number_of_your_default){ 
         c.moveDot(a);// To retrieve the caret to the last row. 
        } 
    // to show line segment on the output with each enter-press key : 
        if(e.getExtendedKeyCode() == KeyEvent.VK_ENTER) 
         System.out.println("!!!!!" + ta.getLineCount() + " " 
         + ta.getText());  
       } 
    // default methods of KeyListener class 
       public void keyReleased(KeyEvent arg0) { 
        // TODO Auto-generated method stub 

       } 

       public void keyTyped(KeyEvent arg0) { 
        // TODO Auto-generated method stub 

       } 
      }); 
//// 

这是我的想法,我希望它是正确的,祝你好运,一个世界,一个上帝,每个解决方案。