Java-JTextPane中的自动缩进 [英] Java - Auto-Indentation in JTextPane
本文介绍了Java-JTextPane中的自动缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Java编写文本编辑器,除自动缩进外,我拥有所有需要的东西.如果换行,我如何使缩进保持不变.我在编辑器窗口中使用的是JTextPane.
I'm making a text-editor in Java, and I have everything I need but auto-indent. How would I make the indentation stay the same if they go to a new line. I'm using a JTextPane for my editor window.
基本上,如果用户输入新行,则我希望新行像上一行一样缩进.
Basically, if a user enters a new line, I want the new line to be indented as was the previous.
这是到目前为止我的缩进代码:
Here is my code for the indentation so far:
注意:我的JTextPane是txt,而doc
部分是JTextPane的 DefaultStyledDocument();
Note: My JTextPane is txt, and the doc
part is the JTextPane'sDefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
TabStop[] tabStops = new TabStop[3];
tabStops[0] = new TabStop(25, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
tabStops[1] = new TabStop(25, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
tabStops[2] = new TabStop(25, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
tabStops[2] = new TabStop(25, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
TabSet tabSet = new TabSet(tabStops);
StyleConstants.setTabSet(attributes, tabSet);
doc.setParagraphAttributes(0, 0, attributes, false);
推荐答案
使用文档过滤器:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class NewLineFilter extends DocumentFilter
{
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
throws BadLocationException
{
if ("\n".equals(str))
str = addWhiteSpace(fb.getDocument(), offs);
super.insertString(fb, offs, str, a);
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
throws BadLocationException
{
if ("\n".equals(str))
str = addWhiteSpace(fb.getDocument(), offs);
super.replace(fb, offs, length, str, a);
}
private String addWhiteSpace(Document doc, int offset)
throws BadLocationException
{
StringBuilder whiteSpace = new StringBuilder("\n");
Element rootElement = doc.getDefaultRootElement();
int line = rootElement.getElementIndex( offset );
int i = rootElement.getElement(line).getStartOffset();
while (true)
{
String temp = doc.getText(i, 1);
if (temp.equals(" ") || temp.equals("\t"))
{
whiteSpace.append(temp);
i++;
}
else
break;
}
return whiteSpace.toString();
}
private static void createAndShowUI()
{
JTextArea textArea = new JTextArea(5, 50);
AbstractDocument doc = (AbstractDocument)textArea.getDocument();
doc.setDocumentFilter( new NewLineFilter() );
JFrame frame = new JFrame("NewLineFilter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new JScrollPane(textArea) );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
在实现文档过滤器上阅读Swing教程中的部分了解更多信息.
这篇关于Java-JTextPane中的自动缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文