Keeping the format on text retrieval

旧街凉风 提交于 2019-12-10 10:54:50

问题


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 is the input pane

Where set :

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);
                }
            }
        });

回答1:


Use the example to merge both Documents http://java-sl.com/tip_merge_documents.html



来源:https://stackoverflow.com/questions/9040294/keeping-the-format-on-text-retrieval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!