JavaFX – CSS editing

As I mentioned in previous posts, in JavaFX you have the power to customize your application UI easily, by using the well known – CSS (cascading style sheets), a language that allows the computer know how to format different controls or scenes. Using the code from here we’re going to tweak it a little bit and apply some formatting using JavaFX css, which is a little different from the CSS people are used to while working with websites.
Here is the JavaFX CSS reference guide, a very useful resource. I must confess that I am terrible at UIs, so the formatting may seem a disaster, but that is not the point. The point is to see how to connect the scene with the CSS file and how to apply some simple formatting.

First, of all we have to connect the .css file to the scene in Java code, like this:

mainScene.getStylesheets().add("/com/wordpress/breekmd/rsc/application.css");

Remember, we are tweaking this code!
Now, we can jump to editing the .css file:

.button {
-fx-border-radius: 2px;
-fx-border-color: #226fbe;
}

.button:hover {
-fx-background: transparent;
-fx-color: #226fbe;
}

.text-field {
-fx-font-family: monospace;
-fx-font-weight: bold;
-fx-border-radius: 4px
}

.root {
-fx-background-image: url("../rsc/img.jpg");
}

.label {
-fx-font-weight: bold;
-fx-alignment: center;
-fx-border-color: white;
-fx-text-fill: black;
-fx-background-color: whitesmoke ;
-fx-background-radius: 4px;
-fx-border-radius: 4px;
}

#putField {
-fx-border-color: red;
-fx-stroke-dash-array: 6 2 10 2;
-fx-text-alignment: center;
}

Where you should be careful:

  • remember the ”-” before fx;
  • a style class selector are preceded by a dot (“.”);
  • an ID selector is preceded by a hashtag (“#”), used if you want to access a specific node (remember to specify the id in the .xml file before [or java]);
  • the selector of the scene is accessed via “.root”; (Be careful, as all nodes descend from root, so some properties of the scene will be applied to other controls)
  • remember the quotation mark when inputting an URL;

Here’s how it looks now (please don’t judge):

css

here’s how it look before (I do like more the first [clean] version, but that’s because I have no taste in UI whatsoever):

optionpricingonline

One comment

Leave a comment