java 更改 JTextArea 中不同行的字体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4905717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
changing the font in a JTextArea for different lines
提问by Ricco
I would like to append differnt lines of font to the JTextArea, however the last font seems to override the other.
我想将不同的字体行附加到 JTextArea,但是最后一个字体似乎覆盖了另一个。
Please help...
请帮忙...
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class test extends JFrame {
private static JTextArea referenceTextArea = new JTextArea(10, 10);
private JPanel panel = new JPanel();
public test() {
this.add(panel);
panel.add(referenceTextArea);
}
public static void textTest() {
referenceTextArea.setFont(new Font("Serif", Font.BOLD, 15));
referenceTextArea.append("line1");
referenceTextArea.append("\n");
referenceTextArea.setFont(new Font("Serif", Font.ITALIC, 30));
referenceTextArea.append("line2");
referenceTextArea.append("\n");
}
public static void main(String[] args) {
test frame = new test();
frame.setVisible(true);
frame.setSize(400, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
textTest();
}
}
采纳答案by Matt Eskridge
Try using JEditorPane / JTextPane
尝试使用 JEditorPane / JTextPane
http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html
http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html
These support HTML formatting. A normal JTextArea's setFont method will just set the font for the entire textarea.
这些支持 HTML 格式。一个普通的 JTextArea 的 setFont 方法只会为整个 textarea 设置字体。