Java 更改JTextPane中特定行的文本对齐方式

Java 更改JTextPane中特定行的文本对齐方式,java,swing,Java,Swing,我正在创建一个剧本编写程序,我遇到了一个问题,我需要根据行内键入的内容更改特定行内的文本对齐方式JPanel。我已经能够从行中提取实际文本并将其放入字符串中,只是无法对齐一行 这是我到目前为止尝试过的,但它给了我一个非法的州例外 StyledDocument doc = textPane1.getStyledDocument(); SimpleAttributeSet center = new SimpleAttributeSet(); StyleConstants.setAlignment(c

我正在创建一个剧本编写程序,我遇到了一个问题,我需要根据行内键入的内容更改特定行内的文本对齐方式
JPanel
。我已经能够从行中提取实际文本并将其放入字符串中,只是无法对齐一行

这是我到目前为止尝试过的,但它给了我一个非法的州例外

StyledDocument doc = textPane1.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
textPane1.getDocument().addDocumentListener(new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent e) {
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        if(ReadText.currentLine(textPane1).contains("INT.")){
            doc.setParagraphAttributes(0,1,center,false);
            System.out.println("Centered");
        }
    }

    @Override
    public void changedUpdate(DocumentEvent arg0) {
            
    }
});
这样做的最佳方法是什么

这给了我一个非法的州例外

StyledDocument doc = textPane1.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
textPane1.getDocument().addDocumentListener(new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent e) {
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        if(ReadText.currentLine(textPane1).contains("INT.")){
            doc.setParagraphAttributes(0,1,center,false);
            System.out.println("Centered");
        }
    }

    @Override
    public void changedUpdate(DocumentEvent arg0) {
            
    }
});
您不能在
文档
侦听器中更新
文档

您需要将代码包装在
SwingUtilities.invokeLater()
中,以便将代码添加到EDT的末尾,并在将所有文本添加到文档后执行

doc.setParagraphAttributes(0,1,center,false);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextPaneAttributes extends JPanel
{

    public TextPaneAttributes()
    {
        setLayout( new BorderLayout() );

        JTextPane textPane = new JTextPane();
        textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight" );

//      DefaultHighlighter highlighter =  (DefaultHighlighter)textPane.getHighlighter();
//      highlighter.setDrawsLayeredHighlights(false);

        //  Define some character and paragraph attributes

        SimpleAttributeSet keyWord = new SimpleAttributeSet();
        StyleConstants.setBold(keyWord, true);

        SimpleAttributeSet green = new SimpleAttributeSet();
        StyleConstants.setForeground(green, Color.GREEN);
        System.out.println(green);
        System.out.println(textPane.getInputAttributes());

        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);

        SimpleAttributeSet left = new SimpleAttributeSet();
        StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);

        //  Change attributes on some existing text

        StyledDocument doc = textPane.getStyledDocument();
        textPane.setCaretPosition(12);
        doc.setCharacterAttributes(0, 3, keyWord, false);
        doc.setCharacterAttributes(8, 5, green, false);
        doc.setParagraphAttributes(20, 1 , center, false);

        //  Add some text with attributes

        try
        {
            doc.insertString(doc.getLength(), "\nNormal text", null);
            doc.insertString(doc.getLength(), "\nGreen text centered", green);
//          int pos = doc.getLength();
//          doc.insertString(pos, "more green text", doc.getCharacterElement(pos-1).getAttributes());
            doc.setParagraphAttributes(doc.getLength(), 1 , center, false);
            doc.insertString(doc.getLength(), "\nKeyword text", keyWord);
            doc.setParagraphAttributes(doc.getLength(), 1 , left, false);

            //  Newly typed text at the end of the document will inherit the
            //  "keyword" attributes unless we remove the attributes

            textPane.setCaretPosition(doc.getLength());
            textPane.getInputAttributes().removeAttributes(keyWord);
        }
        catch(Exception e) {}

        //  Add text pane to frame

        JScrollPane scrollPane = new JScrollPane( textPane );
        scrollPane.setPreferredSize( new Dimension( 200, 250 ) );
        add( scrollPane );

        //  Create a Button panel

        JPanel buttons = new JPanel();
        add(buttons, BorderLayout.PAGE_END);

        //  Add a Bold button

        JButton bold = new JButton( new StyledEditorKit.BoldAction() );
        buttons.add( bold );

        //  Add Right Alignment button

        JButton right = new JButton( new StyledEditorKit.AlignmentAction("Align Right", StyleConstants.ALIGN_RIGHT) );
        buttons.add( right );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TextPaneAttributes());
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}
不确定这是否是你想要的。这将始终设置文档第一行的属性,因为您使用的偏移量为0

下面是一个基本示例,它允许您对文档中的每个段落进行不同的对齐

doc.setParagraphAttributes(0,1,center,false);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextPaneAttributes extends JPanel
{

    public TextPaneAttributes()
    {
        setLayout( new BorderLayout() );

        JTextPane textPane = new JTextPane();
        textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight" );

//      DefaultHighlighter highlighter =  (DefaultHighlighter)textPane.getHighlighter();
//      highlighter.setDrawsLayeredHighlights(false);

        //  Define some character and paragraph attributes

        SimpleAttributeSet keyWord = new SimpleAttributeSet();
        StyleConstants.setBold(keyWord, true);

        SimpleAttributeSet green = new SimpleAttributeSet();
        StyleConstants.setForeground(green, Color.GREEN);
        System.out.println(green);
        System.out.println(textPane.getInputAttributes());

        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);

        SimpleAttributeSet left = new SimpleAttributeSet();
        StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);

        //  Change attributes on some existing text

        StyledDocument doc = textPane.getStyledDocument();
        textPane.setCaretPosition(12);
        doc.setCharacterAttributes(0, 3, keyWord, false);
        doc.setCharacterAttributes(8, 5, green, false);
        doc.setParagraphAttributes(20, 1 , center, false);

        //  Add some text with attributes

        try
        {
            doc.insertString(doc.getLength(), "\nNormal text", null);
            doc.insertString(doc.getLength(), "\nGreen text centered", green);
//          int pos = doc.getLength();
//          doc.insertString(pos, "more green text", doc.getCharacterElement(pos-1).getAttributes());
            doc.setParagraphAttributes(doc.getLength(), 1 , center, false);
            doc.insertString(doc.getLength(), "\nKeyword text", keyWord);
            doc.setParagraphAttributes(doc.getLength(), 1 , left, false);

            //  Newly typed text at the end of the document will inherit the
            //  "keyword" attributes unless we remove the attributes

            textPane.setCaretPosition(doc.getLength());
            textPane.getInputAttributes().removeAttributes(keyWord);
        }
        catch(Exception e) {}

        //  Add text pane to frame

        JScrollPane scrollPane = new JScrollPane( textPane );
        scrollPane.setPreferredSize( new Dimension( 200, 250 ) );
        add( scrollPane );

        //  Create a Button panel

        JPanel buttons = new JPanel();
        add(buttons, BorderLayout.PAGE_END);

        //  Add a Bold button

        JButton bold = new JButton( new StyledEditorKit.BoldAction() );
        buttons.add( bold );

        //  Add Right Alignment button

        JButton right = new JButton( new StyledEditorKit.AlignmentAction("Align Right", StyleConstants.ALIGN_RIGHT) );
        buttons.add( right );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TextPaneAttributes());
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
/*
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}

从我在那个帖子中看到的,那里的代码和我原来帖子中的代码是一样的,但它对我来说不起作用,我认为代码将整个文本窗格对齐到特定的一面,我只需要更改一行的对齐方式。所以,当用户在面板中键入时,没有办法更改行的对齐方式吗?例如,在他们开始新的生产线之后?