在JTextArea中剪切和粘贴 [英] Cut and Paste in JTextArea

查看:219
本文介绍了在JTextArea中剪切和粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,它要求JTextArea中只能包含165个字符. 我已经强加了那个条件.我使用了一个静态计数器来计数在textarea中输入的字符数,并且还编码为处理这种情况,当用户从文本中删除任何字符串时,必须考虑所选字符串的长度来增加计数器.

I'm developing an application which requires that only 165 characters to be in the JTextArea. I've imposed that condition. I've used a static counter for counting number of characters entered in the textarea and also coded to handle the condition when user deletes any string from the text the counter must be incremented by considering length of the string selected.

但是,现在我想通过按"Ctrl + X"和"Ctrl + V"来处理用户执行剪切"或粘贴"选项时的情况.我知道JTextComponent的默认方法是在JTextArea中继承的,但是我想获取剪切文本并知道剪切文本的长度,以便减少为字符维护的计数器,并在粘贴适当数量时增加计数器.

However now I want to handle the condition when user performs 'cut' or 'paste' option by pressing 'Ctrl+X' and 'Ctrl+V'. I know that default methods from JTextComponent are inherited in JTextArea but I want to get the cut text and know the length of the cut text so as to decrement the counter maintained for characters and increment it while pasting by appropriate amount.

推荐答案

听起来您需要使用

It sounds like you need to use DocumentListener to track the changes. The events in the document listener will tell you how many characters are added/removed in any given change, and also gives you a reference to the Document that is backing the text area.

以下是名为textAreaJTextArea的示例文档侦听器实现:

The following is an example document listener implementation for a JTextArea called textArea:

textArea.getDocument().addDocumentListener( new DocumentListener() {
  public void changedUpdate( DocumentEvent e )
  {
  }

  public void insertUpdate( DocumentEvent e )
  {
    System.out.println( "insertUpdate: Added " + e.getLength() + 
        " characters, document length = " + e.getDocument().getLength() );
  }

  public void removeUpdate( DocumentEvent e )
  {
    System.out.println( "removeUpdate: Removed " + e.getLength() +
        " characters, document length = " + e.getDocument().getLength() );
  }
});

此侦听器将检测剪切和粘贴以及按键.

This listener will detect cut and pastes as well as key presses.

这篇关于在JTextArea中剪切和粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆