简体   繁体   中英

Java - removing specific characters from text in jeditorpane

I would appreciate some help modifying a function!

The aims: Make an array list of specific characters. Write a method to remove the characters specified in the arraylist from text JEditorpane.

So Far: Made an arraylist of characters, Wrote a function to remove the characters. made a gui that includes jeditorpane

The issue: The function works, and remove characters that I println to console via a string.

I am struggling to make the function remove the characters from the text document that i open into JEditorpane.

The code in short:

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



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

documentpane is the name of my jeditorpane

if I change, document.chatAt, to test.chatAt, (which is printing to console, this works.

        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);

Thanks for any help in advance.

As Document doesn't have charAt method you first need to extract the content of the document. This can be done by the following:

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

Then when using your for-loop with content it should work. So your code would look like this:

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);

How about this :

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

You can use document.getText(0,docuemnt.getLength()) As lino suggested. But I prefer regex cause you do not have to loop and check, Using StringBuilder instead of concatenation is a better practice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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