【问题标题】:JTextArea row limitJTextArea 行限制
【发布时间】:2012-08-22 01:23:03
【问题描述】:

所以,我有一个JTextArea

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

考虑到所有这些,有没有办法做到这一点?

【问题讨论】:

  • 试试这个链接:stackoverflow.com/questions/479182/…>

标签: java swing jtextarea documentlistener


【解决方案1】:

为什么不添加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);
     }
  }
});

【讨论】:

【解决方案2】:

你需要定义一个关键的监听器,在里面我们肯定需要定义实现的方法,下一个代码是我的解决方案,希望对你有帮助。

////
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

                }
            });
////

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

【讨论】:

    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2010-10-03
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    相关资源
    最近更新 更多