3

我正在尝试用 java 制作一个计算器程序,但我不确定如何在我的 JTextArea 中将文本居中。我试过搜索谷歌和 YouTube,但我什么也没找到。这是我的源代码:

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

public class Sect1 extends JTextArea{
    public static final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
    
    public Sect1(){
        this.setBounds(ss.width / 4, ss.height / 5, 100, 100);
        this.setLineWrap(true);
        this.setWrapStyleWord(true);
    }
}
4

1 回答 1

2

您可能希望考虑使用 JTextField 在单行中输入文本并使用以下方法将其内容居中:

setHorizontalAlignment(JTextField.CENTER);

但是,如果您需要 JTextArea 之类的东西来引入多行文本,请使用JTextPane或其子类 JEditorPane,它可以让您对书面文本进行更多的自定义和控制。

在 JTextPane 中居中文本:

JTextPane textPane = new JTextPane();

StyledDocument documentStyle = textPane.getStyledDocument();
SimpleAttributeSet centerAttribute = new SimpleAttributeSet();
StyleConstants.setAlignment(centerAttribute, StyleConstants.ALIGN_CENTER);
documentStyle.setParagraphAttributes(0, documentStyle.getLength(), centerAttribute, false);
于 2021-03-03T10:13:07.053 回答