6 Years
Discussion Span
Last Post by murali_quest

Although you can in theory put pretty much anything you like on the clipboard, it can be difficult.
You can use XMLEncoder to convert your Swing objects to a simple text String that is really easy to put on the clipboard, and XMLDecoder to re-create the object from the clipboard text. Documentation is in the usual places.


I am able to copy and paste strings using java.awt.datatransfer.StringSelection.
By using my custom class with implementing Transferable,ClipboardOwner i can copy and paste image also(Using DataFlavor.imageFlavor). It was easy to do. In a same way how i can do it for Swing components.. I dont have any idea on XMLEncoder and
XMLDecoder... Sorry to say this.. Is there any other way?


Is there any other way?

Yes, probably, maybe a custom DataFlavor...
But it's so easy and generalisable to convert any bean-like object to a plain String and back, that IMHO it's the easiest way to get the job done.
Here's a little bit of code to illustrate the XML encode/decode stuff...

public static String objectToXML(Object o) {
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      XMLEncoder en = new XMLEncoder(os);
      return os.toString();
   public static Object  objectFromXML(String s) {
      ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
      XMLDecoder de = new XMLDecoder(is);
      return de.readObject();

   public static void main(String[] args) {

      JButton jb = new JButton("Hello, world");
      jb.setBounds(0, 0, 100, 10);

      String s = objectToXML(jb);

      Object o = objectFromXML(s);
Votes + Comments

Thanks a lot. I have used XMLEncoder and XMLDecoder. It is working finely
for swing components. But it is not working for Netbeans Custom classes.Now i
want to encode and decode netbeans visual api widget classes.

After encoding swing JButton in to xml i can able to see the following.

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_18" class="java.beans.XMLDecoder">
<object class="java.awt.Button">
<void property="background">
<object class="java.awt.Color">
<void property="bounds">
<object class="java.awt.Rectangle">
<void property="actionCommand">
<void property="label">
<void property="name">

But when i encoded Netbeans visual api widget in to xml,only body is coming without contents..as follows.

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_18" class="java.beans.XMLDecoder">

Why it is not supporting for custom classes i dont know. If i will get any idea that will be helpful for me.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.