[英]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.