Bootstrap with Javafx

Bootstrap with JavaFX

Rendering Bootstrap inside a JavaFX WebView

Bootstrap is an HTML based framework.

So to use Bootstrap in JavaFX, use JavaFX's HTML rendering component WebView to render Bootstrap HTML/CSS and JavaScript.

Sample Application

Sample application performing a basic integration of Bootstrap and a JavaFX UI.

The JavaFX buttons on the top of the screen navigate around a WebView page to render different kinds of Bootstrap components.

jumbotron

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class BaseJump extends Application {
private static final String BOOTSTRAP_PREFIX = "http://getbootstrap.com/components/#";

private enum Anchor { progress, jumbotron, badges, pagination }

@Override public void start(Stage stage) throws Exception {
final WebView webview = new WebView();

final ToolBar nav = new ToolBar();
for (Anchor anchor : Anchor.values()) {
nav.getItems().add(
new NavButton(
anchor,
webview
)
);
}

VBox layout = new VBox();
layout.getChildren().addAll(
nav,
webview
);

Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) { launch(args); }

private class NavButton extends Button {
public NavButton(final Anchor anchor, final WebView webview) {
setText(anchor.toString());

setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
webview.getEngine().load(BOOTSTRAP_PREFIX + anchor.toString());
}
});
}
}
}

Additional, slightly unrelated question

Is it possible to intercept button click events from a web view?

Yes. You can attach click handlers in Java code through the w3c DOM API access WebEngine provides. See the WebEngine documentation for details:

Access to Document Model

The WebEngine objects create and manage a Document Object Model (DOM) for their Web pages. The model can be accessed and modified using Java DOM Core classes. The getDocument() method provides access to the root of the model. Additionally DOM Event specification is supported to define event handlers in Java code.

The following example attaches a Java event listener to an element of a Web page. Clicking on the element causes the application to exit:

EventListener listener = new EventListener() {
public void handleEvent(Event ev) {
Platform.exit();
}
};

Document doc = webEngine.getDocument();
Element el = doc.getElementById("exit-app");
((EventTarget) el).addEventListener("click", listener, false);

However, for me often is is easier to handle interfacing with w3c documents using JavaScript (specifically jQuery), rather than Java. Here is an example of issuing from Java code, a jQuery call to provide click handlers in a WebView.

On Fextile (Bootstrap look for native JavaFX controls)

Why not just port bootstrap.css to conform to the javafx naming conventions?

Because:

  • There is more to bootstrap than just the css, it's a full responsive UI framework with JavaScript based active controls and a user extension mechanism.
  • Rendering in WebView will render the bootstrap html in JavaFX exactly the same as if it were in a web browser, so why port when you already have something which will work perfectly with no extra effort?
  • It's a moving target, the bootstrap.css trunk project gets many contributions from hundreds of developers, it would be difficult to keep up with that with a home-grown JavaFX port, though if you selected just a smaller subset of bootstrap features keeping in sync would be easier.

Still, it is possible to do the port (as linked in Philippe's answer), and that is what Takayuki Okazaki has created in his Fextile project: "Twitter Bootstrap like UI framework for JavaFX. Apply themes to your application just like Twitter Bootstrap via JavaFX CSS.". Don't expect an exact match with bootstrap in HTML, but it should allow your JavaFX controls which don't use HTML to have a pretty close look to what you would achieve with bootstrap in HTML.

You could also create a hybrid application, where some parts of the UI are from HTML with bootstrap and some are rendered from JavaFX controls using Fextile. If you applied such an approach to the sample application in this answer, then the JavaFX buttons "progress", "jumbotron", etc. would look like their HTML bootstrap counterparts, giving the whole application a more consistent look and feel.

Also, note that there is a similar project for Foundation styles for JavaFX, as announced in this Oracle JavaFX forum post. This project mimics the basic Foundation look for native JavaFX controls. For some usages, adopting Foundation styles may be more appropriate than Bootstrap styles as the project is smaller in scope than Bootstrap (as far as I know).

Here is a Q&A (from the Oracle JavaFX forum post) on how to creating the Foundation style (so somebody can get a relative idea of what is involved for extending Fextile for additional Bootstrap style features). Note that the Q&A is a little old and since then a CSS analyzer has been added to SceneBuilder:

1) How difficult was this work?

No at all: the whole experience was very pleasant and very easy to do.
This is my first JavaFX app (a map style editor with real time
preview)

2) Was it very time consuming?

No: using the preview ScenceBuilder 1.1 the styles are updated on the
fly - the SceneBuilder could do with a built in CSS editor, but that's
only minor: the workflow was quite simple anyway

3) For a simple port do you think that you need any design skills at
all, or could anybody have really done this who knows a bit of
css/html/javafx?

Anyone can do this: my background is server side code - I don't do
much in the way of front ends - I know JS and HTML very well but my
CSS leaves a lot to me desired: so basically if I can do it ...

4) Was the difference between the javafx css syntax and the html css
syntax a major pain or not really an issue?

Once I got used to it, made no difference although I do keep
forgetting to add '-fx-' and the -fx-text-fill I always type as
-fx-text-color ...

5) Similarly did a lack of a one-to-one correspondence between html
document tags (e.g. the header tags) and JavaFX complicate this?

No

6) Will the upcoming rich text support in JavaFX 8 simplify (or make
possible) more of these kinds of ports?

I need to have a look at this: as I said I'm a complete beginner with
JavaFX so I'm still catching up on the current implementation.

The bootstrap styles would be really nice: a lot of people who I've
showed the app to are quite amazed when I tell them its Java and not
an embedded web app.

Bootstrap Style in javaFx application?

Check this one https://github.com/aalmiray/bootstrapfx

This adds support for some of the Bootstrap styles for your JavaFX Controls.

Add a Bootstrap css stylesheet to Gluon scenebuilder for JavaFX

You'd have to put the bootstrapfx-core JAR (https://search.maven.org/search?q=org.kordamp.bootstrapfx) in the classpath where SceneBuilder can find it. I believe SB has a menu option for adding JARs to the classpath.

Next you have to apply the bootstrapfx stylesheet, I'd suggest applying to the root of the the node hierarchy, or the container/pane where you want Bootstrap styles to be used. The stylesheet "org/kordamp/bootstrapfx/bootstrapfx.css" is available from the classpath.

Finally add style classes to the components you want to update. A lists of available styles can be found in the README. https://github.com/kordamp/bootstrapfx#supported-css-classes

How to create a 'bootstrap' style alert with JavaFX

I would use a TextFlow with an embedded Text child in an HBox. Of course, on your button, you would want a graphic rather than an X character.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>
<?import javafx.scene.text.TextFlow?>


<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="120.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
<children>
<HBox prefHeight="400.0" prefWidth="600.0" style="-fx-border-color: red; -fx-background-color: pink; -fx-border-radius: 6;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<TextFlow prefHeight="200.0" prefWidth="200.0" HBox.hgrow="ALWAYS">
<children>
<Text strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-fill: red;" text="Alert messages will appear here...">
<font>
<Font name="Microsoft YaHei UI" size="14.0" />
</font>
</Text>
</children>
<padding>
<Insets bottom="12.0" left="12.0" right="12.0" top="12.0" />
</padding>
</TextFlow>
<VBox>
<children>
<Button mnemonicParsing="false" style="-fx-background-color: transparent;" text="X" />
</children>
</VBox>
</children>
<padding>
<Insets bottom="12.0" left="12.0" right="12.0" top="12.0" />
</padding>
</HBox>
</children>
</AnchorPane>

Bootstrap style alert box

Bootstrap Javafx 2.0 with Weld

ShaggyInjun, you refer to the Initializable interface which indicates you were trying to integrate with the FXMLLoader. All of the information below assumes you are using FXML for your interface definition and only discusses issues around injecting values into FXML controllers.

The FXMLLoader has the concept of a controller factory, which you should use to integrate the controller instantiation with your dependency injection system. There is a brief discussion of controller factories in Oracle's Mastering FXML Tutorial. Andy demonstrates definition of such a factory for Guice in his blog and there is a comprehensive integration of Guice in FXML on github.


For Weld you will need to implement a similar controller factory callback mechanism to realize the dependency injection functionality which Weld provides. The article by Matthieu Brouillard that you linked in a comment FXML & JavaFX—Fueled by CDI & JBoss Weld would seem to provide all of the information you need to both initialize Weld and interface Weld into the FXMLLoader controller factory mechanism. Specifically, the following code is the Weld equivalent of Andy Till's FXML based injection mechanism:

public class FXMLLoaderProducer {
@Inject Instance<Object> instance;
@Produces public FXMLLoader createLoader() {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(new Callback<Class<?>, Object>() {
@Override public Object call(Class<?> param) {
return instance.select(param).get();
}
});
return loader;
}
}

Even when an FXMLoader controller factory is used, I believe it is the FXMLLoader that is instantiating the controller. So in those cases, you should not make of annotations like @PostConstruct because they only apply when the dependency injection system is maintaining the lifecycle of the object - and that is not the case if the FXMLLoader creates the controller.

There is one other alternative, and that it is to explicitly set the controller to be used by the FXMLLoader using setController. This would allow you to have your dependency injection system instantiate (and inject into) controllers using whatever means it wishes and then you could subsequently pass the instantiated controller to your FXMLLoader. In such cases anotations like @PostConstruct should work as the dependency injection system is now maintaining the objects lifecycle (and @PostConstruct would be invoked by the dependency injection system after the Controller has been created and before you pass the Controller through to the FXMLLoader).


I'll post Andy's Guice based solution here as it is a small and simple example of how similar injection is accomplished in Guice (in case his blog goes offline):

class GuiceControllerFactory implements Callback<Class<?>, Object> {
private final Injector injector;
public GuiceControllerFactory(Injector anInjector) {
injector = anInjector;
}
@Override public Object call(Class<?> aClass) {
return injector.getInstance(aClass);
}
}

E003 type error with Bootstrap Glyphicons and JavaFX WebView

Bootstrap glyph icons show in Java 8.

This is (likely) because JavaFX in Java 8 adds @font-face support which was not present in Java 7 (JavaFX 2.2).

Related JavaFX issue tracker issues which added support in Java 8:

  • RT-10343 CSS add support for CSS3 @font-face (uses JavaFX css styles).
  • RT-17428 WebView-component to render CSS @font-face declarations (uses HTML css styles).

JavaFX css themes

Guigarage provides 3 out-of-the-box styles.

  • AquaFX, a native look & feel for Mac OSX
  • AeroFX, that gives you the look of a Windows Forms app for Windows 7
  • Flatter, a flat-design gui theme

Feel free to complete this list by answering the question.



Related Topics



Leave a reply



Submit