我想知道在jeditorpane中是否有一种方法可以将制表符转换为空格,就像在IDE中工作时看到的那样。我不想设置制表符大小,这很容易实现。我想用它们相当于空格替换制表符。因此,例如,如果我的制表符长度为5个空格,则每次创建制表符时都会立即用5个空格替换所有制表符。有什么想法吗?
DocumentFilter
添加到AbstractDocument
中,以便在将文本插入Document
时用空格替换制表符。import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class TabToSpaceFilter extends DocumentFilter
{
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
throws BadLocationException
{
replace(fb, offset, 0, text, attributes);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attributes)
throws BadLocationException
{
// In case someone tries to clear the Document by using setText(null)
if (text == null)
text = "";
super.replace(fb, offset, length, text.replace("\t", " "), attributes);
}
private static void createAndShowGUI()
{
JTextArea textArea = new JTextArea(5, 20);
AbstractDocument doc = (AbstractDocument) textArea.getDocument();
doc.setDocumentFilter( new TabToSpaceFilter() );
JFrame frame = new JFrame("Integer Filter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new java.awt.GridBagLayout() );
frame.add( new JScrollPane(textArea) );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
EventQueue.invokeLater( () -> createAndShowGUI() );
}
}