gpt4 book ai didi

java - JTextPane 动态缩进!!!情况

转载 作者:行者123 更新时间:2023-12-01 16:35:34 27 4
gpt4 key购买 nike

我尝试动态更新 Jtextpane 中的左缩进。但我不能!这是我尝试过的!

DefaultStyledDocument document = (DefaultStyledDocument) textpane.getDocument();
Element element = document.getCharacterElement(start);
AttributeSet attribs = element.getAttributes();
attribs.containsAttribute(StyleConstants.LeftIndent, 20);
document.setCharacterAttributes(start, length, attribs, true);

最佳答案

以下是如何将 Action 添加到 JButton 以缩进文本段落:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextPaneIndent extends JPanel
{
public TextPaneIndent()
{
setLayout( new BorderLayout() );

JTextPane textPane = new JTextPane();
textPane.setText("one\ntwo\nthree\nfour");
textPane.setPreferredSize( new Dimension(200, 220) );
JScrollPane scrollPane = new JScrollPane( textPane );
scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
add( scrollPane );

// Create a Button panel

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

// Add Indent button

JButton indent = new JButton( new LeftIndentAction("Indent", 10) );
add( indent );

// Add Outdent button

JButton outdent = new JButton( new LeftIndentAction("Outdent", -10) );
add( outdent );
}

class LeftIndentAction extends StyledEditorKit.StyledTextAction
{
private float value;

public LeftIndentAction(String name, float value)
{
super(name);
this.value = value;
}

public void actionPerformed(ActionEvent e)
{
JEditorPane editor = getEditor(e);

if (editor != null)
{
StyledDocument doc = getStyledDocument( editor );
int offset = editor.getCaretPosition();
Element paragraph = doc.getParagraphElement( offset );
AttributeSet as = paragraph.getAttributes();
float indent = StyleConstants.getLeftIndent( as );
indent += value;

MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setLeftIndent(attr, indent);
setParagraphAttributes(editor, attr, false);
}
}
}

public static void main(String[] args)
{
TextPaneIndent frame = new TextPaneIndent();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}

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

public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

关于java - JTextPane 动态缩进!!!情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61954548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com