4

私は Java でテキスト エディターを作成しており、自動インデント以外に必要なものはすべて揃っています。新しい行に移動した場合、インデントを同じままにするにはどうすればよいですか。エディタ ウィンドウに JTextPane を使用しています。

基本的に、ユーザーが新しい行を入力した場合、前の行と同じように新しい行をインデントする必要があります。

これまでのインデントのコードは次のとおりです。

注: 私の JTextPane は txt で、そのdoc部分は JTextPane のDefaultStyledDocument();

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

1 に答える 1

4

ドキュメント フィルターを使用する:

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 チュートリアルのセクションを参照してください。

于 2013-04-07T23:56:05.107 に答える