如何突出显示替换所选单词的单词?

时间:2015-04-05 17:16:27

标签: java swing highlight jtextpane

此代码用以下新代码替换所选单词:

String search = jTextField1.getText();
String replaced = jTextPane.getText().replace(search, jTextField2.getText());
jTextPane.setText(replaced);

将新单词的背景设置为黄色的最简单方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用属性:

Simple AttributeSet changed = new SimpleAttributeSet();
StyleConstants.setForeground(changed, Color.RED);
StyleConstants.setBackground(changed, Color.YELLOW);

//  Change attributes on some text

StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(20, 4, changed, false);

查找/替换逻辑检出:Find/Replace, Highlight Words。您可以修改突出显示代码以使用属性。

答案 1 :(得分:1)

 private void changeAllActionPerformed(java.awt.event.ActionEvent evt) {
        int j = 0;
        int i = 0;
        int index = 0;
        String search = jTextField1.getText();
        String replaced = jTextPane.getText().replace(search, jTextField2.getText());
        jTextPane.setText(replaced); 
        String newtext = jTextField2.getText();

        try{
            if(!jTextField2.getText().isEmpty()){
                while(i != -1){
                        i = jTextPane.getText().indexOf(newtext, j);
                    if(i == -1)
                        break;
                    if(evt.getSource() == changeAll|| evt.getSource() == changeAllButton){
                        jTextPane.select(i, i + newtext.length());   
                    }
                    Color c = Color.YELLOW;
                    Style s = jTextPane.addStyle("TextBackground", null);
                    StyleConstants.setBackground(s, c);
                    StyledDocument d = jTextPane.getStyledDocument();
                    d.setCharacterAttributes(jTextPane.getSelectionStart(), jTextPane.getSelectionEnd() - jTextPane.getSelectionStart(), jTextPane.getStyle("TextBackground"), false);
                    j = i + search.length();
                    index++;
                }
                if (index > 0){
                    jTextPane.grabFocus();
                    jTextPane.setCaretPosition(jTextPane.getText().indexOf(newtext, 0) );
                } 
        } catch (Exception e){
            jLabel.setText("error");
            System.err.print(e);
}