Saturday, September 27, 2008

Setting Look And Feel when start up

This is how you can set the look and feel style for your java pplication.
It'll set the look and feel according to the platform regardless of java default style.
This is very useful when you want to start java application from another application and to make the same style with window default.
This method must have called when start the application. Just call this in main implementation

public static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(getPreferredLookAndFeelForOS());
} catch (ClassNotFoundException e) {

} catch (InstantiationException e) {

} catch (IllegalAccessException e) {

} catch (UnsupportedLookAndFeelException e) {

}
}



private static String getPreferredLookAndFeelForOS() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.indexOf("mac") || osName.indexOf("win"){
return UIManager.getSystemLookAndFeelClassName();
} else {
return UIManager.getCrossPlatformLookAndFeelClassName();
}
}

Thursday, September 25, 2008

Parsing xml string to dom4j Document

This is how to parse xml message to dom4j Document object

public static Document parseXml(String xmlRequest) throws DocumentException {
Reader source = new StringReader(xmlRequest);
SAXReader reader = new SAXReader();
return reader.read(source);
}

Reading value from Properties File

This method shows you how to read value from the properties file from java. We need to read some parameter from the properties file in order to allow user to customize the functionalities such as socket host and port number, user define error message, UI messages and so on.

You may have a singleton class to handle the specific properties file and have the public method to get the value by the key.

public String readFromProperties(String filePath, String keyName) {
Properties properties;
String value = null;
try {

properties = new Properties();
FileInputStream fis = new FileInputStream(filePath);
if (fis != null) {
properties.load(fis);
value = properties.getProperty(keyName);
fis.close();
}
} catch (FileNotFoundException e) {
// handle if file not found
} catch (IOException e) {
// handle reading properties files errors
}
return value;
}