保持文本检索的格式

我正在制作一个具有聊天function的网络应用程序。 在聊天中,我有一个用于显示消息的JTextPane和一个用于输入的消息。 然后我有一些按钮,允许在输入文本上添加样式(粗体,斜体,字体大小,颜色)。 文本在输入窗格上正确格式化,但是当移动到显示窗格时(一旦按下正确的JButton ),它只具有最后一个字符的格式。 如何在保持原始格式的同时移动文本?例如,如果我在输入上写“Hello Worl d ”,则显示“Hello Worl d”

textPane是输入窗格

设置地点:

 final SimpleAttributeSet set = new SimpleAttributeSet(); 

使输入文本加粗的代码(与添加其他样式相同):

 bold.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { StyledDocument doc = textPane.getStyledDocument(); if (StyleConstants.isBold(set)) { StyleConstants.setBold(set, false); bold.setSelected(false); } else { StyleConstants.setBold(set, true); bold.setSelected(true); } textPane.setCharacterAttributes(set, true); } }); 

用于将文本从输入窗格移动到显示窗格的代码:

 getInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String input = textPane.getText(); textPane.setText(""); if(!input.endsWith("\n")){ input+="\n"; } StyledDocument doc = displayPane.getStyledDocument(); int offset = displayPane.getCaretPosition(); try { doc.insertString(offset, input, set); } catch (BadLocationException ex) { Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex); } } }); 

使用该示例合并两个文档http://java-sl.com/tip_merge_documents.html