请问如何在JeditorPane中给字体设定不同颜色和字型?  (例如: 在JeditorPane中有ABC, 我要将A设定为红色及粗体, B设定为兰色及斜体, C为绿色和带有下划线), 以及如何用代码把盘符中的.JPG和.GIF添加到图象JEditorPane中?
以上应该如何实现请给出代码(只要实现此功能的主要代码)和相应的注释.
万分谢谢!

解决方案 »

  1.   

    想实现你所说的功能,JEditorPane有点弱了,建议使用JTextPane,以下是测试代码:import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import java.io.*;public class Test {
      JFrame frame, frame2;
      JTextPane textPane,textPane2;
      Icon image;  public Test(){
        frame = new JFrame("JTextPane");
        textPane = new JTextPane();
        image = new ImageIcon("");
      }

    /**
     * 插入
     */
      public void insert(String str, AttributeSet attrSet) {
        Document doc = textPane.getDocument();
        str ="\n" + str ;
        try {
          doc.insertString(doc.getLength(), str, attrSet);
        }
        catch (BadLocationException e) {
          System.out.println("BadLocationException: " + e);
        }
      }
    /**
     * 设置
     */
      public void setDocs(String str,Color col,boolean bold,int fontSize) {
        SimpleAttributeSet attrSet = new SimpleAttributeSet();
        StyleConstants.setForeground(attrSet, col);
        //颜色
        if(bold==true){
          StyleConstants.setBold(attrSet, true);
        }//字体类型
        StyleConstants.setFontSize(attrSet, fontSize);
        //字体大小
        insert(str, attrSet);
      }  public void gui() {
        textPane.insertIcon(image); //将图片插入到光标位置
        setDocs("第一行的文字",Color.red,false,20);
        setDocs("第二行的文字",Color.BLACK,true,25);
        setDocs("第三行的文字",Color.BLUE,false,20);
        frame.getContentPane().add(textPane, BorderLayout.CENTER);
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }});
        frame.setSize(200,300);
        frame.setVisible(true);
      }
      public static void main(String[] args) {
        Test test = new Test();
        test.gui();
      }
    }