[英]Tabs, newlines, DocumentFilters and eclipse text
因此,關於這個問題,我還有另一個問題。
一旦應用了此修復程序,請轉到記事本,使用一些隨機字符鍵入一堆選項卡和換行符,然后將其粘貼到我的程序中,一切都將變好。
但是,作為帶有一堆標簽和換行符的最接近的文本,我嘗試將代碼本身的一部分粘貼到JTextArea。 所有選項卡和換行符都停留在那里,沒有被過濾掉。
盡管我的用戶可能不會將eclipse代碼粘貼到我的程序中,但是我不確定eclipse代碼是唯一的例外。 所以我想知道為什么會這樣。
另外,我希望我的代碼能夠過濾掉空格字符以外的空白字符,並將其轉換為空格字符。 我認為tab和newline是唯一的,但是如果還有更多,請告訴我。
無論如何,要使其正常運行,我必須進行哪些更改?
這是固定的SSCCE:
package core;
import java.awt.BorderLayout; import java.awt.Dimension; import java.io.FileNotFoundException; import java.io.IOException;
import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter;
class DefaultDocFilter extends DocumentFilter {
public void insertString(FilterBypass fb, int offs,String str, AttributeSet a) throws BadLocationException
{
if ((fb.getDocument().getLength() + str.length()) <= 2000)
{
str = str.replaceAll("\n", " ");
str = str.replaceAll("\t", " ");
fb.insertString(offs, str, a);
}
else
{
int spaceLeft = 2000 - fb.getDocument().getLength();
if (spaceLeft <= 0)
return;
str = str.substring(0, spaceLeft);
str = str.replaceAll("\n", " ");
str = str.replaceAll("\t", " ");
fb.insertString(offs, str, a);
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException
{
if (str.equals("\n") || str.equals("\t"))
{
str = "";
}
if ((fb.getDocument().getLength() + str.length() - length) <= 2000)
{
str = str.replaceAll("\n", " ");
str = str.replaceAll("\t", " ");
fb.replace(offs, length, str, a);
}
else
{
int spaceLeft = 2000 - fb.getDocument().getLength() + length;
if (spaceLeft <= 0)
return;
fb.replace(offs, length, str.substring(0,spaceLeft).replaceAll("\n", " "), a);
}
} }
public class Main {
public static JFrame mWindow;
public static void main(String[] args) throws FileNotFoundException, IOException
{
//create main window
mWindow = new JFrame("title");
mWindow.setSize(1000, 800);
mWindow.setMinimumSize(new Dimension(1000, 800));
mWindow.setLocationRelativeTo(null);
mWindow.setLayout(new BorderLayout());
mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea a = new JTextArea();
AbstractDocument doc = (AbstractDocument) a.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());
a.setLineWrap(true);
a.setWrapStyleWord(true);
mWindow.add(a);
mWindow.pack();
mWindow.setVisible(true);
mWindow.repaint();
mWindow.validate();
} }
它是Java 1.7。 創建一個新項目,包核心,文件Main。
文檔過濾器是第一類,它應用於您將看到的JTextArea。 您需要的一切都在該課程中。
編輯:我修復了SSCCE。 此外,僅當您嘗試粘貼更多適合JTextArea的字符時才出現此問題(我將限制設置為2000)。 然后,tas和換行符將不會被過濾掉。
在replace
方法的方法的else
部分中,僅替換“ \\ n”,而不替換“ \\ t”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.