【问题标题】:JTextPane make new lineJTextPane 换行
【发布时间】:2013-03-10 02:01:45
【问题描述】:

我可以用这段代码换行

StringBuilder sb = new StringBuilder();  
sb.append("<span style=\"color:black\">--------------</span> <br>");  
sb.append("<span style=\"color:red\">Error." + e.toString() + "</span> <br>");
sshoutput.setContentType("text/html");  
sshoutput.setText(sb.toString());

但是当我再次对另一个文本执行此操作时,它只显示第二个文本不是在此之后

错误。” + e.toString()

对不起,我的英语不是很好。希望你能理解。

【问题讨论】:

  • 你能用你的代码详细说明一下异常吗?
  • 为什么StringBuilder对象是br而你却在做sb.append
  • 很遗憾,我不太明白。你的意思是你想在现有文本中添加另一个文本,但它会替换它吗?
  • 对不起,我写得很快 String Builder is sb
  • ^是的,这是我的问题

标签: java html swing jtextpane htmleditorkit


【解决方案1】:

我现在正在使用 JTextPane,我所做的是:

JTextPane pane = new JTextPane();
StyledDocument doc = pane.getStyledDocument();

所以我可以在任何地方插入字符串:

doc.insertString(STRING POSITION, STRING, null);

我对这种方法没有例外。还有一种简单的方法来设置字母样式:

SimpleAttributeSet set = new SimpleAttributeSet();
//Here you modify set. Set is collection of
//various style instructions
//(letters color, bolded, italic, background color etc.)
//You modify set using StyleConstants class.
doc.setCharacterAttributes(START, LENGTH, set, true);

编辑:一个示例,它创建文本窗格并在其中写入样式为“Hello World”:

JTextPane pane = new JTextPane();
StyledDocument doc = pane.getStyledDocument();
doc.insertString(0, "Hello", null);
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstans.setForeground(set, Color.RED);
doc.setCharacterAttributes(0, 5, set, true);
doc.insertString(5, "World!", null);
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstans.setForeground(set, Color.BLUE);
doc.setCharacterAttributes(5, 6, set, true);

使用 GridLayout(1, 1) 将其添加到 JPanel,您应该会看到带有红色字符串“Hello”和蓝色字符串“World”的文本窗格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多