我想弄个像QQ一样的能在文字中插入图片的,也能显示图片的文本框,感觉上JTextArea好像不行,
想过自己写一个,不过好像先来问问大家有没有现成的这样的东西?如果没有的话,自己写,最简单的构造思路是怎么样的?

解决方案 »

  1.   

    能不能具体告诉我JTextPane的具体用法呢
    我没有用过,谢谢了!
      

  2.   

    我想插入图片,可是直接用insertIcon()不行呀
    不知道有没有知道的高手告诉我该怎么做呢?
      

  3.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import java.io.*;public class Test {
      JFrame frame;
      JTextPane textPane;
      File file;
      Icon image;  public Test(){
        frame = new JFrame("JTextPane");
        textPane = new JTextPane();
        file = new File("/classes/test/icon.gif");
        image = new ImageIcon(file.getAbsoluteFile().toString());
      }  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();
      }
    }
      

  4.   

    while(true){
         thesocket.receive(packet);
         int i=0;
         //String str=new String();
     String s=new String(packet.getData(),0,packet.getLength());
     //StringTokenizer str=new StringTokenizer(s,"/a");  
     System.out.println("run"); 
    jTextPane.setText(s+"\n");
    jTextPane.insertIcon(new ImageIcon(ClassLoader.getSystemResource("6.gif")));
    System.out.println("end");
    // jTextPane.setText(str.nextToken());

     
     packet.setLength(buffer.length);
     }  
    这是我写的代码的一部分,因为是和socket的一起用的
    我这样直接插入不行吗?
    一定要设置Document么?
      

  5.   

    插如图片的方法insertIcon(image)用JTextPane的实例来调用,如果要设置文本的样式则必须使用Document,这才是JTextPane的精华。
      

  6.   

    可是我解释调用JTextPane的对象
    还是不能显示图片亚,我也给别人看了,还是不能显示图片
    但是我纯粹test一个JTextPane就能显示图片
    但是就是在我这个程序里不能
    我都不知道怎么回事了?
    所以求救亚
      

  7.   

    我举个例子你看:
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;public class useImage2 extends JApplet
    {
      Image image1,image2;  public void init()
      {
        JPanel panel1=(JPanel)getContentPane();
        panel1.setLayout(new BorderLayout());    image1=getImage(getCodeBase(),"ontbvsa.gif");
        ImageIcon icon1=new ImageIcon(image1);
        image2=getImage(getCodeBase(),"offtbvsa.gif");
        ImageIcon icon2=new ImageIcon(image2);    JButton imagebutton=new JButton(icon2);
        imagebutton.setPressedIcon(icon1);
      
        panel1.add(imagebutton,BorderLayout.CENTER);
      }

      

  8.   

    你是不是使用了textPane.setEditable(false);方法?
    我以前在做一个项目时也遇到这样的问题,最后不得不继承JTextPane类,然后重写其中的图片显示部分。
      

  9.   

    我的确是使用了textPane.setEditable(false);
    当然不能编辑这个窗口。
    怎么重写呢?
    难道要让我在上面加个jlabel对象,然后在上面添加图标,在把它添加到jtextPane上么?
    我现在打得是这个主意
    不知道又没有别的方法呢?
    简单的最好
    谢谢了哦!!!
      

  10.   

    下面这个类继承了JTextPane,改写了其中插入图片的方法,解决了在不可编辑的状态下插入图片的问题import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;/**
     * <p>Title: JTextPane在不可编辑状态下还能插入图片</p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2003</p>
     * <p>Company: </p>
     * @author not attributable
     * @version 1.0
     */public class Pro_TextPane extends JTextPane {
      public Pro_TextPane() {
        super();
        setEditorKit(createDefaultEditorKit());
      }  public Pro_TextPane(StyledDocument doc) {
        this();
        setStyledDocument(doc);
      }  public void replaceSelection(String content) {
        replaceSelection(content, null);
      }  private void replaceSelection(String content, AttributeSet attr) {
        Document doc = getStyledDocument();
        if (doc != null) {
          try {
            Caret caret = getCaret();
            int p0 = Math.min(caret.getDot(), caret.getMark());
            int p1 = Math.max(caret.getDot(), caret.getMark());
            if (doc instanceof AbstractDocument) {
              if (attr != null) {
                ( (AbstractDocument) doc).replace(p0, p1 - p0, content, attr);
              }
              else {
                ( (AbstractDocument) doc).replace(p0, p1 - p0, content,
                                                  getInputAttributes());
              }
            }
            else {
              if (p0 != p1) {
                doc.remove(p0, p1 - p0);
              }
              if (content != null && content.length() > 0) {
                doc.insertString(p0, content,
                                 attr != null ? attr : getInputAttributes());
              }
            }
          }
          catch (BadLocationException e) {
            UIManager.getLookAndFeel().provideErrorFeedback(Pro_TextPane.this);
          }
        }
      }  public void insertComponent(Component c) {
        MutableAttributeSet inputAttributes = getInputAttributes();
        inputAttributes.removeAttributes(inputAttributes);
        StyleConstants.setComponent(inputAttributes, c);
        replaceSelection(" ", inputAttributes.copyAttributes());
        inputAttributes.removeAttributes(inputAttributes);
      }  public void insertIcon(Icon g) {
        MutableAttributeSet inputAttributes = getInputAttributes();
        inputAttributes.removeAttributes(inputAttributes);
        StyleConstants.setIcon(inputAttributes, g);
        replaceSelection(" ", inputAttributes.copyAttributes());
        inputAttributes.removeAttributes(inputAttributes);
      }}
      

  11.   

    import javax.swing.*;
    import javax.swing.text.*;import java.awt.*;              //for layout managers
    import java.awt.event.*;        //for action and window eventsimport java.net.URL;
    import java.io.IOException;public class TextSampler extends JFrame
                                 implements ActionListener {
        private String newline = "\n";
        protected static final String textFieldString = "JTField";
        protected static final String passwordFieldString = "JPasswordField";    protected JLabel actionLabel;    public TextSampler() {
            super("TextSampler");        //Create a regular text field.
            JTextField textField = new JTextField(10);
            textField.setActionCommand(textFieldString);
            textField.addActionListener(this);        //Create a password field.
            JPasswordField passwordField = new JPasswordField(10);
            passwordField.setActionCommand(passwordFieldString);
            passwordField.addActionListener(this);        //Create some labels for the fields.
            JLabel textFieldLabel = new JLabel(textFieldString + ": ");
            textFieldLabel.setLabelFor(textField);
            JLabel passwordFieldLabel = new JLabel(passwordFieldString + ": ");
            passwordFieldLabel.setLabelFor(passwordField);        //Create a label to put messages during an action event.
            actionLabel = new JLabel("Type text and then Return in a field.");
    actionLabel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));        //Lay out the text controls and the labels.
            JPanel textControlsPane = new JPanel();
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();        textControlsPane.setLayout(gridbag);        JLabel[] labels = {textFieldLabel, passwordFieldLabel};
            JTextField[] textFields = {textField, passwordField};
            addLabelTextRows(labels, textFields, gridbag, textControlsPane);        c.gridwidth = GridBagConstraints.REMAINDER; //last
            c.anchor = GridBagConstraints.WEST;
            c.weightx = 1.0;
            gridbag.setConstraints(actionLabel, c);
            textControlsPane.add(actionLabel);
            textControlsPane.setBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Text Fields"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)));        //Create a text area.
            JTextArea textArea = new JTextArea(
                    "This is an editable JTextArea " +
                    "that has been initialized with the setText method. " +
                    "A text area is a \"plain\" text component, " +
                    "which means that although it can display text " +
                    "in any font, all of the text is in the same font."
            );
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            areaScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            areaScrollPane.setPreferredSize(new Dimension(250, 250));
            areaScrollPane.setBorder(
                BorderFactory.createCompoundBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Plain Text"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)),
                    areaScrollPane.getBorder()));        //Create an editor pane.
            JEditorPane editorPane = createEditorPane();
            JScrollPane editorScrollPane = new JScrollPane(editorPane);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));        //Create a text pane.
            JTextPane textPane = createTextPane();
            JScrollPane paneScrollPane = new JScrollPane(textPane);
            paneScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            paneScrollPane.setPreferredSize(new Dimension(250, 155));
            paneScrollPane.setMinimumSize(new Dimension(10, 10));        //Put the editor pane and the text pane in a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  editorScrollPane,
                                                  paneScrollPane);
            
            splitPane.setOneTouchExpandable(true);
            JPanel rightPane = new JPanel();
            rightPane.add(splitPane);
            rightPane.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Styled Text"),
                            BorderFactory.createEmptyBorder(5,5,5,5)));
            //Put everything in the applet.
            JPanel leftPane = new JPanel();
            BoxLayout leftBox = new BoxLayout(leftPane, BoxLayout.Y_AXIS);
            leftPane.setLayout(leftBox);
            leftPane.add(textControlsPane);
            leftPane.add(areaScrollPane);        JPanel contentPane = new JPanel();
            BoxLayout box = new BoxLayout(contentPane, BoxLayout.X_AXIS);
            contentPane.setLayout(box);
            contentPane.add(leftPane);
            contentPane.add(rightPane);
            setContentPane(contentPane);
        }    private void addLabelTextRows(JLabel[] labels,
                                      JTextField[] textFields,
                                      GridBagLayout gridbag,
                                      Container container) {
            GridBagConstraints c = new GridBagConstraints();
            c.anchor = GridBagConstraints.EAST;
            int numLabels = labels.length;        for (int i = 0; i < numLabels; i++) {
                c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
                c.fill = GridBagConstraints.NONE;      //reset to default
                c.weightx = 0.0;                       //reset to default
                gridbag.setConstraints(labels[i], c);
                container.add(labels[i]);            c.gridwidth = GridBagConstraints.REMAINDER;     //end row
                c.fill = GridBagConstraints.HORIZONTAL;
                c.weightx = 1.0;
                gridbag.setConstraints(textFields[i], c);
                container.add(textFields[i]);
            }
        }    public void actionPerformed(ActionEvent e) {
            String prefix = "You typed \"";
            if (e.getActionCommand().equals(textFieldString)) {
                JTextField source = (JTextField)e.getSource();
                actionLabel.setText(prefix + source.getText() + "\"");
            } else {
                JPasswordField source = (JPasswordField)e.getSource();
                actionLabel.setText(prefix + new String(source.getPassword())
                                    + "\"");
            }
        }    private JEditorPane createEditorPane() {
            JEditorPane editorPane = new JEditorPane();
            editorPane.setEditable(false);
            String s = null;
            try {
                s = "file:"
                    + System.getProperty("user.dir")
                    + System.getProperty("file.separator")
                    + "/html/TextSamplerHelp.html";
                URL helpURL = new URL(s);
                displayURL(helpURL, editorPane);
            } catch (Exception e) {
                System.err.println("Couldn't create help URL: " + s);
            }
      

  12.   


            return editorPane;
        }    private void displayURL(URL url, JEditorPane editorPane) {
            try {
                editorPane.setPage(url);
            } catch (IOException e) {
                System.err.println("Attempted to read a bad URL: " + url);
            }
        }    private JTextPane createTextPane() {
            JTextPane textPane = new JTextPane();
            String[] initString =
                    { "This is an editable JTextPane, ", //regular
                      "another ", //italic
                      "styled ", //bold
                      "text ", //small
                      "component, ", //large
                      "which supports embedded components..." + newline,//regular
                      " " + newline, //button
                      "...and embedded icons..." + newline, //regular
                      " ",  //icon
                      newline + "JTextPane is a subclass of JEditorPane that " +
                        "uses a StyledEditorKit and StyledDocument, and provides " +
                        "cover methods for interacting with those objects."
                     };        String[] initStyles = 
                    { "regular", "italic", "bold", "small", "large",
                      "regular", "button", "regular", "icon",
                      "regular"
                    };        initStylesForTextPane(textPane);        Document doc = textPane.getDocument();        try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString[i],
                                     textPane.getStyle(initStyles[i]));
                }
            } catch (BadLocationException ble) {
                System.err.println("Couldn't insert initial text.");
            }        return textPane;
        }    protected void initStylesForTextPane(JTextPane textPane) {
            //Initialize some styles.
            Style def = StyleContext.getDefaultStyleContext().
                                            getStyle(StyleContext.DEFAULT_STYLE);        Style regular = textPane.addStyle("regular", def);
            StyleConstants.setFontFamily(def, "SansSerif");        Style s = textPane.addStyle("italic", regular);
            StyleConstants.setItalic(s, true);        s = textPane.addStyle("bold", regular);
            StyleConstants.setBold(s, true);        s = textPane.addStyle("small", regular);
            StyleConstants.setFontSize(s, 10);        s = textPane.addStyle("large", regular);
            StyleConstants.setFontSize(s, 16);        s = textPane.addStyle("icon", regular);
            StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
            StyleConstants.setIcon(s, new ImageIcon("images/Pig.gif"));        s = textPane.addStyle("button", regular);
            StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
            JButton button = new JButton(new ImageIcon("images/sound.gif"));
            button.setMargin(new Insets(0,0,0,0));
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Toolkit.getDefaultToolkit().beep();
                }
            });
            StyleConstants.setComponent(s, button);
        }    public static void main(String[] args) {
            JFrame frame = new TextSampler();        frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });        frame.pack();
            frame.setVisible(true);
        }
    }
    这是完整的代码,好一阵让我感叹,原来java的灵活性呀,代码还能钻孔子