用java swing 中的jTextPane实现局部文本改色添加删除线等操作

用java swing 中的jTextPane实现局部文本改色添加删除线等操作,以下是执行图片:


实现代码如下:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 2011-2-21, 9:04:46
 */

package desktopapplicationmenu;

import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

/**
 *
 * @author
 */

public class NewJFrame extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        jTextPane1.setText("http://www.my400800.cn ");
        // jEditorPane1.("<html>   <head>   <style type=´text/css´>     A{text-decoration: none; color: #000000; }     A:hover {text-decoration: underline; color: #FF0000; }   </style> </head> <body>     <a href=\"www.google.com\">Google</a><br>     <a href=\"www.yahoo.com\">Yahoo!</a> </body> </html>  ");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">

    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplicationmenu.DesktopApplicationMenu.class).getContext().getResourceMap(NewJFrame.class);
        jButton1.setLabel(resourceMap.getString("jButton1.label")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextPane1.setText(resourceMap.getString("jTextPane1.text")); // NOI18N
        jTextPane1.setName("jTextPane1"); // NOI18N
        jScrollPane2.setViewportView(jTextPane1);

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(247, 247, 247)
                        .addComponent(jButton2)
                        .addGap(33, 33, 33)
                        .addComponent(jButton1)
                        .addGap(55, 55, 55)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 838, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(39, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addGap(37, 37, 37))
        );

        jButton3.getAccessibleContext().setAccessibleName(resourceMap.getString("jButton3.AccessibleContext.accessibleName")); // NOI18N

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        Document doc = jTextPane1.getStyledDocument();
        int istartPosition = 1;
        int iType = 1;
        int iPK = 1;
        SetAddText(istartPosition, iType, iPK, jTextPane1, doc);

        //        String str = "";
//        Document doc = jTextPane1.getStyledDocument();
//
//        str = jTextPane1.getText();
//
//
//        int iStart = str.indexOf("7891");
//        int iEnd = str.indexOf("1011");
//        try {
//            String strReplace = str.substring(iStart, iEnd);
//            System.out.println(strReplace);
//
//            doc.remove(iStart, strReplace.replace("\n", "").length());
//
//            doc.insertString(iStart, strReplace, getAddAttrSet());
//        } catch (BadLocationException ex) {
//            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//        jTextPane1.setSelectionStart(iStart);
//        jTextPane1.setSelectionEnd(iEnd);
//        jTextPane1.setSelectionEnd(iStart);
//        //DefaultStyledDocument.ElementEdit;
//        jTextPane1.setSelectedTextColor(Color.red);


    }                                       

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String str = "";
        for (int i = 0; i < 10; i++) {
            str += "" + i + (i + 1) + (i + 2) + (i + 3) + (i + 4) + "\r\n";
        }
        Document doc = jTextPane1.getStyledDocument();
        jTextPane1.setText(str);



    }                                       

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        Document doc = jTextPane1.getStyledDocument();
        int istartPosition = 1;
        int iType = 1;
        int iPK = 1;
        SetDelText(istartPosition, iType, iPK, jTextPane1, doc);
    }

    /**
     * @param args the command line arguments
     */

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration

    /**
     * 返回 新添加属性样式
     *
     * @return
     */

    public SimpleAttributeSet getAddAttrSet() {
        SimpleAttributeSet attrSet = new SimpleAttributeSet();

        StyleConstants.setItalic(attrSet, false);
        StyleConstants.setUnderline(attrSet, false);
        StyleConstants.setFontSize(attrSet, 16);
        StyleConstants.setForeground(attrSet, Color.red);
        return attrSet;
    }

    /**
     * 返回 删除加属性样式
     *
     * @return
     */

    public SimpleAttributeSet getDelAttrSet() {
        SimpleAttributeSet attrSet = new SimpleAttributeSet();

        StyleConstants.setItalic(attrSet, true);
        StyleConstants.setUnderline(attrSet, true);
        StyleConstants.setFontSize(attrSet, 16);
        StyleConstants.setForeground(attrSet, Color.BLUE);
        StyleConstants.setStrikeThrough(attrSet, true);
        return attrSet;
    }

    /**
     * 设定添加文本颜色
     * @param istartPosition 字符开始检索位置
     * @param iType          类型:属性、段位、状态
     * @param iPK         设定属性PK
     */

    public void SetAddText(int istartPosition, int iType, int iPK, javax.swing.JTextPane jTextPaneObj, Document doc) {
        String strReplaceForm = "";
        istartPosition = 10;
        String strReplaceTo = "http://www.my400800.cn";
        SimpleAttributeSet attrSet = getAddAttrSet();
        SetText(istartPosition, jTextPaneObj, doc, strReplaceForm, strReplaceTo, attrSet);
    }

    /**
     * 设定添加文本颜色
     * @param istartPosition 字符开始检索位置
     * @param iType          类型:属性、段位、状态
     * @param iPK         设定属性PK
     */

    public void SetDelText(int istartPosition, int iType, int iPK, javax.swing.JTextPane jTextPaneObj, Document doc) {
        String strReplaceForm = "http://www.my400800.cn";
        String strReplaceTo = "http://www.my400800.cn";
        //istartPosition = 10;
        SimpleAttributeSet attrSet = getDelAttrSet();
        SetText(istartPosition, jTextPaneObj, doc, strReplaceForm, strReplaceTo, attrSet);
    }

    /**
     * 设定实际控件上的显示状态
     * @param istartPosition  文本检索开始位置
     * @param jTextPaneObj    文本存放控件
     * @param doc             属性设定样式雷
     * @param strReplaceForm  替换前内容(如果该值为空,重该位置直接插入)
     * @param strReplaceTo    替换后内容
     * @param attrSet
     */

    public void SetText(int istartPosition, javax.swing.JTextPane jTextPaneObj, Document doc, String strReplaceForm, String strReplaceTo, SimpleAttributeSet attrSet) {
        try {
            String str = jTextPaneObj.getText();
            int iStart = istartPosition;
            if (strReplaceForm != null && strReplaceForm.length() > 0) {
                istartPosition = str.replace("\n", "").indexOf(strReplaceForm, istartPosition);
                iStart = istartPosition;
                int iEnd = iStart + strReplaceTo.length();
                String strReplace = str.substring(iStart, iEnd);
                System.out.println(strReplace);
                doc.remove(iStart, strReplace.replace("\n", "").length());
            }
            doc.insertString(iStart, strReplaceTo, attrSet);
            jTextPane1.setSelectionStart(iStart);
            jTextPane1.setSelectionEnd(iStart + 1);

        } catch (BadLocationException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


posted @ 2011-02-22 16:05  ljlxyf  阅读(1187)  评论(0编辑  收藏  举报