gpt4 book ai didi

java - 向 JTextPane 添加多个文本,而不是用另一个文本替换每个文本

转载 作者:行者123 更新时间:2023-11-29 04:31:14 26 4
gpt4 key购买 nike

我似乎真的找不到要求将多个文本添加到 JTextPane 的问题。此外,append 不适用于 JTextPane。

konsol = new JTextPane();
konsol.setText("something" + "\n");

这是我试过的方法,但它只是替换了旧文本。怎么办?

最佳答案

我以前用过类似的方法,我可以分享给你:

class JTextPaneExample {

public static void main(String[] args) {
JTextPane tp = new JTextPane();
tp.setSize(250, 250);
appendToPane(tp, "Hello Java,\n\n", Color.BLACK);
appendToPane(tp, "Hello Suing,\n\n\n\n", Color.BLUE);
appendToPane(tp, "Hello......,\n", Color.RED);
JFrame f = new JFrame();

f.setSize(300, 300);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.add(tp);
f.setVisible(true);
}

public static void appendToPane(JTextPane tp, String txt, Color clr) {
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, clr);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Serif");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(txt);
}
}

结果是这样的

JTextPane multiple line

关于java - 向 JTextPane 添加多个文本,而不是用另一个文本替换每个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739045/

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