Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6710045
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T07:57:17+00:00 2026-05-26T07:57:17+00:00

I have this code to demonstrate the problem: public static void main(String[] args) {

  • 0

I have this code to demonstrate the problem:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new JEditorPane("text/html", "Hello cruel world<br>\n<font color=red>Goodbye cruel world</font><br>\n<br>\nHello again<br>\n"));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

If you select all the text that appears in the frame once the app starts, you can copy it and paste it into MS Word, Apple’s Pages, or Mail and the text is formatted correctly. But if you paste it into a pure text editor such as TextEdit, Smultron, or a Skype chat window all the pasted content is on one line.

What can I do to make the text copied to the clipboard able to be pasted with newlines preserved?

I’m running my code on Mac OS X 10.7

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T07:57:17+00:00Added an answer on May 26, 2026 at 7:57 am

    After getting no answers, I rolled up my sleeves and did a lot of research and learning. The solution is to make a custom TransferHandler for the component, and massage the HTML text manually. It wasn’t easy to work all this out, which could account for the zero answers I got.

    Here’s a working solution:

    import javax.swing.*;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLEditorKit;
    import javax.swing.text.html.parser.ParserDelegator;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import java.io.Reader;
    import java.io.StringReader;
    import java.util.ArrayList;
    
    public class ScratchSpace {
    
        public static void main(String[] args) {
            final JFrame frame = new JFrame();
            final JEditorPane pane = new JEditorPane("text/html", "<html><font color=red>Hello</font><br>\u2663<br>World");
            pane.setTransferHandler(new MyTransferHandler());
            frame.getContentPane().add(pane);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
    }
    
    class MyTransferHandler extends TransferHandler {
    
        protected Transferable createTransferable(JComponent c) {
            final JEditorPane pane = (JEditorPane) c;
            final String htmlText = pane.getText();
            final String plainText = extractText(new StringReader(htmlText));
            return new MyTransferable(plainText, htmlText);
        }
    
        public String extractText(Reader reader) {
            final ArrayList<String> list = new ArrayList<String>();
    
            HTMLEditorKit.ParserCallback parserCallback = new HTMLEditorKit.ParserCallback() {
                public void handleText(final char[] data, final int pos) {
                    list.add(new String(data));
                }
    
                public void handleStartTag(HTML.Tag tag, MutableAttributeSet attribute, int pos) {
                }
    
                public void handleEndTag(HTML.Tag t, final int pos) {
                }
    
                public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, final int pos) {
                    if (t.equals(HTML.Tag.BR)) {
                        list.add("\n");
                    }
                }
    
                public void handleComment(final char[] data, final int pos) {
                }
    
                public void handleError(final String errMsg, final int pos) {
                }
            };
            try {
                new ParserDelegator().parse(reader, parserCallback, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String result = "";
            for (String s : list) {
                result += s;
            }
            return result;
        }
    
    
        @Override
        public void exportToClipboard(JComponent comp, Clipboard clip, int action) throws IllegalStateException {
            if (action == COPY) {
                clip.setContents(this.createTransferable(comp), null);
            }
        }
    
        @Override
        public int getSourceActions(JComponent c) {
            return COPY;
        }
    
    }
    
    class MyTransferable implements Transferable {
    
        private static final DataFlavor[] supportedFlavors;
    
        static {
            try {
                supportedFlavors = new DataFlavor[]{
                        new DataFlavor("text/html;class=java.lang.String"),
                        new DataFlavor("text/plain;class=java.lang.String")
                };
            } catch (ClassNotFoundException e) {
                throw new ExceptionInInitializerError(e);
            }
        }
    
        private final String plainData;
        private final String htmlData;
    
        public MyTransferable(String plainData, String htmlData) {
            this.plainData = plainData;
            this.htmlData = htmlData;
        }
    
        public DataFlavor[] getTransferDataFlavors() {
            return supportedFlavors;
        }
    
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            for (DataFlavor supportedFlavor : supportedFlavors) {
                if (supportedFlavor == flavor) {
                    return true;
                }
            }
            return false;
        }
    
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (flavor.equals(supportedFlavors[0])) {
                return htmlData;
            }
            if (flavor.equals(supportedFlavors[1])) {
                return plainData;
            }
            throw new UnsupportedFlavorException(flavor);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I just encountered this (made up code to demonstrate the problem): public ICollection<string> CreateCollection(int
I have this code #include <iostream> using namespace std; int main(int argc,char **argv) {
I have this code :- using (System.Security.Cryptography.SHA256 sha2 = new System.Security.Cryptography.SHA256Managed()) { .. }
I have the following situation. This is a code snippet, edited to demonstrate the
I have this code in jQuery, that I want to reimplement with the prototype
I have this code: chars = #some list try: indx = chars.index(chars) except ValueError:
I have this code that performs an ajax call and loads the results into
I have this code: CCalcArchive::CCalcArchive() : m_calcMap() { } m_calcMap is defined as this:
I have this code: myVariable which I want to change into trace(myVariable: + myVariable);
I have this code while($row = mysql_fetch_row($result)) { echo '<tr>'; $pk = $row[0]['ARTICLE_NO']; foreach($row

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.