Search code examples
javastringswingjlabel

Java convert String to JLabel


A JLabel in java can be turned into a String (using .toString())

Similarly i want to take that string which i have read from a file and turn it back into a JLabel again.

(if this is not possible would their be another way to store a JLabel in a file and then recreate it exactly again)


Solution

  • I agree with MadProgrammer that XMLEncoder and XMLDecoder are the way to go.

    This answer gives you a good idea of how to use both of them, but I changed this code to specifically use JLabel.

    String toString(JLabel jl) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      XMLEncoder e = new XMLEncoder(baos);
      e.writeObject(jl);
      e.close();
      return new String(baos.toByteArray());
    }
    
    JLabel fromString(String str) {
        XMLDecoder d = new XMLDecoder(new ByteArrayInputStream(str.getBytes()));
        JLabel label = (JLabel) d.readObject();
        d.close();
        return label;
    }