保持文本检索的格式 [英] Keeping the format on text retrieval
问题描述
我正在制作一个具有聊天功能的网络应用程序。在聊天中,我有一个 JTextPane
用于显示消息,还有一个用于输入。然后我有一些按钮,允许在输入文本上添加样式(粗体,斜体,字体大小,颜色)。文本在输入窗格上正确格式化,但是当移动到显示窗格时(一旦按下正确的 JButton
),它只具有最后一个字符的格式。如何在保持原始格式的同时移动文本?例如,如果我在输入上写Hello Worl d ,则显示Hello Worl d
I am making a network application that has a chat function. On the chat I have one JTextPane
for displaying messages and one more for input. Then I have some buttons that allow to add style on the input text(bold,italic,font size,colour). The text is formatted correctly on input pane , although when moved to the display pane(once the correct JButton
is pressed) it only has the format of last character. How can I move the text while keeping its original format?For example if I write "Hello Worl d" on the input , display shows "Hello Worl d"
textPane是输入窗格
textPane is the input pane
设置位置:
final SimpleAttributeSet set = new SimpleAttributeSet();
使输入文本变为粗体的代码(与添加其他样式相同):
Code for making input text bold(same of adding other styles) :
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);
}
});
将文本从输入窗格移动到显示窗格的代码:
code for moving text from the input pane to the display pane :
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
Use the example to merge both Documents http://java-sl.com/tip_merge_documents.html
这篇关于保持文本检索的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!