java保留文本检索的格式
我正在制作一个具有聊天功能的网络应用程序。在聊天中我有一个JTextPane
用于显示消息,另一个用于输入。然后我有一些按钮,可以在输入文本上添加样式(粗体、斜体、字体大小、颜色)。文本在输入窗格上的格式正确,但当移动到显示窗格(一旦按下正确的JButton
)时,它只有最后一个字符的格式。如何在保持原始格式的同时移动文本?例如,如果我在输入上写下“Hello World,显示屏将显示“Hello Worl d”
文本窗格是输入窗格
设置位置:
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);
}
}
});
共 (0) 个答案