Coding java gui using Swing designing it with CSS

Building a GUI in java isn't complicated having netbeans as a great Swing gui builder.

But what if we want to have some of the design left out of the code in a CSS file?

As when building a java applet which should blend with a website, out best shot will be to use the same CSS file in the swing code as we use for the website.

How can we design the GUI components using swing?

We will use TK-UI's SwingCSSEngine (which is opensourced).

Their documentation can be reached using the following link:

http://tk-ui.sourceforge.net/user-guide/cssengine/swingcssengine.html

How is it done?

  1. Download the libraries: http://sourceforge.net/projects/tk-ui/files/org.akrogen.tkui.css.swing/
  2. Copy the jar files (also those in their "lib" directory [excluding the commons if you wish]) into your project's (the swing project) lib directory.
  3. In the code before initializing the swing components (a method which is actually called initComponents() in the netbeans IDE) add the following code:


/* Setting up the CSS styles */

// Create Swing CSS Engine

CSSEngine engine = new CSSSwingEngineImpl();

// Parse style sheet

try {

// Getting the css from a file

InputStream is = class-classNameYouAreRunning.class.getClassLoader().getResource("swing.css").openStream();

engine.parseStyleSheet(is);

} catch (IOException e) {

e.printStackTrace();

}


In the above code we assume a file named "swing.css" exists and resides in our classpath.

  1. After the initialization of the swing components (after initComponents() method in netbeans) add the following code:



JFrame frame = this.getFrame();

// Apply Styles

engine.applyStyles(frame, true);

frame.pack();

frame.setVisible(true);

Comments

Popular posts from this blog

How to read Android apk contents

Start Working with AutoIT

SCummVM for Android