Saturday, December 27, 2014

How to Generate Random Colors in Java


This is the code I used to generate random colors in JPanel. You can adjust the values for hue & saturation to get the color you want.

Don't forget to import java.awt.Color & java.util.Random
public Color generateColor(){
        Color color;
        Random random = new Random();
        //to get rainbow, pastel colors
        final float hue = random.nextFloat();
        final float saturation = 1.0f; //1.0 for brilliant, 0.0 for dull
        final float luminance = 0.6f; //1.0 for brighter, 0.0 for black
        color = Color.getHSBColor(hue, saturation, luminance);
        return color;
}

Usage: MyPanel.setBackground(generateColor());

Thursday, December 25, 2014

Writing an HTML file from a template using Java

Create a template and save as template.html .
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>[TITLE]</title></head><body>[BODY]</body></html>
Put a tag like [TAG] for any dynamic content and then do something like this:
File htmlTemplateFile = new File("path/template.html");String htmlString = FileUtils.readFileToString(htmlTemplateFile);String title = "New Page";String body = "This is Body";htmlString = htmlString.replace("[TITLE]", title);htmlString = htmlString.replace("[BODY]", body);File newHtmlFile = new File("path/new.html");FileUtils.writeStringToFile(newHtmlFile, htmlString);

Note: You will need to import org.apache.commons.io.FileUtils to do this.