Java allows you to create Graphical User Interfaces (GUIs). There are several systems for doing this, including one called Swing and one called JavaFX. BlueJ allows development using either. JavaFX is the newer of the two, and has some relevant BlueJ features so we will explore a JavaFX GUI.
JavaFX expects that your whole application will be a JavaFX application, starting with a main class which extends JavaFX's Application class. We provide a template class (available under the options when you click New Class) for getting started, but in this tutorial we have provided a pre-written application called CatView.
To run any JavaFX Application sub-class, simply right-click it in BlueJ and you will see the the CatView class and select .
menu item. You should use this in favour of creating the class manually or using Application.launch. BlueJ restarts the user virtual machine, and runs the target application. Use this command now: right-clickA dialog will appear, asking if you want to invoke all methods in this project on the JavaFX thread. JavaFX requires that any interactions with the GUI happen on the JavaFX thread, so if you want to invoke any JavaFX-related methods (e.g. from the object bench or codepad), BlueJ needs to do this on the JavaFX thread. Say
. You should then see a GUI window pop up with a picture of a cat.You can invoke methods on the JavaFX application object as you would for any other object. Right-click on the red catView1 object and select . Since we said "Use JavaFX thread" in the previous dialog, this method will be run on the JavaFX thread. (If you need to change this, the option is specified per-project in the Preferences dialog, in the Miscellaneous tab.)
JavaFX uses Cascading Style Sheets (CSS) to style the interface, such as adjusting sizes, spacing, colors and so on. BlueJ has support for creating and editing CSS files. You can create a new CSS file by going to the Edit menu for the main window and clicking cats and the .css extension will be added automatically. Once you click OK, you will see that a silver CSS item named cats.css gets added to the class diagram.
. You will be asked for a name: type inThere are two more steps needed: we need to tell the JavaFX GUI to use that CSS file, and we need to put some content in it. To get JavaFX to use the CSS file, add the following line near the bottom of the makeScene method, before the last return scene; line:
scene.getStylesheets().add("cats.css");
And lastly, we need to supply the content for the CSS file. To edit the file, double-click on the silver cats.css file, just like for classes. Then add in the following CSS text:
.image-wrapper {
-fx-padding: 20px;
-fx-background-color: white;
}
Now try running the JavaFX application again. You should find that the image gets a white border around it because of the CSS file we have added.