繁体   English   中英

Java-从jeditorpane中的文本中删除特定字符

[英]Java - removing specific characters from text in jeditorpane

我希望能对修改功能有所帮助!

目的:列出特定字符的数组。 编写一种方法,以从文本JEditorpane中删除arraylist中指定的字符。

到目前为止:创建了一个字符数组列表,编写了一个删除字符的函数。 制作了一个包含jeditorpane的gui

问题:该函数有效,并删除了我通过字符串println控制台的字符。

我正在努力使函数从我打开到JEditorpane的文本文档中删除字符。

简短的代码:

     private static ArrayList<Character> special = new  ArrayList<Character>(Arrays.asList('a','b','h'));



    public class removing implements ActionListener {
    public void actionPerformed(ActionEvent e) {

documentpane是我的jeditorpane的名称

如果我将document.chatAt更改为test.chatAt(正在打印到控制台,则可以。

        Document document = documentpane.getDocument();

        String test = "hello world?";
        String outputText = "";

        for (int i = 0; i < document.getLength(); i++) {
            Character c = new Character(document.charAt(i));
            if (!special.contains(c))
                outputText += c;
            else
                outputText += " ";
        }
        System.out.println(outputText);

感谢您的任何帮助。

由于Document没有charAt方法,因此您首先需要提取文档的内容。 这可以通过以下方式完成:

String content = document.getText(0, document.getLength());

然后,在将for-loop用于content它应该可以工作。 因此,您的代码如下所示:

Document document = documentpane.getDocument();
String content = document.getText(0, document.getLength());
String outputText = "";
for (int i = 0; i < content.length(); i++) {
    Character c = new Character(content.charAt(i));
    if (!special.contains(c))
       outputText += c;
    else
       outputText += " ";
}
System.out.println(outputText);

这个怎么样 :

    String outputText =document.getText(0,docuemnt.getLength()).replaceAll("[a|b|c]"," ");
   //set regex that you want 
    System.out.println(outputText);

您可以按照lino的建议使用document.getText(0,docuemnt.getLength())。 但是我更喜欢使用正则表达式,因为您不必循环检查,使用StringBuilder而不是连接是更好的做法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM