Format a color to HTML RGB color format (e.g. #FF0000 for Color.red)
/*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the License). You may not use this file except in
* compliance with the License.
*
* You can get a copy of the License at http://www.thinkingrock.com.au/cddl.html
* or http://www.thinkingrock.com.au/cddl.txt.
*
* When distributing Covered Code, include this CDDL Header Notice in each file
* and include the License file at http://www.thinkingrock.com.au/cddl.txt.
* If applicable, add the following below the CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* The Original Software is ThinkingRock. The Initial Developer of the Original
* Software is Avente Pty Ltd, Australia.
*
* Portions Copyright 2006-2007 Avente Pty Ltd. All Rights Reserved.
*/
import java.awt.Color;
import java.io.Reader;
import java.io.StringReader;
import java.util.logging.Logger;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.html.HTMLEditorKit;
/**
* Some static utility methods for HTML stuff.
*
* @author Jeremy Moore
*/
public final class HTML {
/**
* Utility method to format a color to HTML RGB color format (e.g. #FF0000 for Color.red).
* @param color The color.
* @return the HTML RGB color string.
*/
public static final String format(Color c) {
String r = (c.getRed() < 16) ? "0" + Integer.toHexString(c.getRed()) : Integer.toHexString(c.getRed());
String g = (c.getGreen() < 16) ? "0" + Integer.toHexString(c.getGreen()) : Integer.toHexString(c.getGreen());
String b = (c.getBlue() < 16) ? "0" + Integer.toHexString(c.getBlue()) : Integer.toHexString(c.getBlue());
return "#" + r + g + b;
}
/**
* Utility method to convert HTML to text.
* @param html The string containing HTML.
* @return a String containing the derived text .
*/
public static final String html2text(String html) {
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
try {
Reader reader = new StringReader(html);
kit.read(reader, doc, 0);
return doc.getText(0, doc.getLength());
} catch (Exception e) {
return "";
}
}
}
Related examples in the same category