📜 ⬆️ ⬇️

JavaFX 2.0 beta - we write client application in Java. On the example of the menu in the Mac-style

image At the JavaOne conference in San Francisco last year, Oracle announced the JavaFX 2.0 technology. A few days ago, the world saw Java FX 2.0 Beta. JavaFX is a natural step in the evolution of the Java client platform. The technology provides developers with a cross-platform tool for creating functionally rich and attractive applications.
Built into Java technology, JavaFX offers a rich graphical and media API with support for hardware-based graphics accelerators and a large selection of new components: controls, graphics, multimedia, and an embedded browser.
Of the obvious advantages of JavaFX 2.0 is the ability to create applications without learning new technologies, using familiar development tools and, of course, all the traditional advantages of Java. For corporations, the use of Java technology on the server and client sides will reduce integration risks.
Of the minuses: unfortunately, the beta version was released only for Windows, but the release of the supported platforms will expand.

But it is better to see once than to hear 100 times.
Let's try writing together a taskbar with Mac-style buttons.

image
')
The first step is installing JavaFX. The easiest way is to download the NetBeans plugin ( http://www.oracle.com/technetwork/java/javafx/downloads/index.html ), which will include JavaFX2.0, examples and templates. If you do not use NetBeans, it is enough to download the SDK from the same link and connect jfxrt.jar from it as a library to your project.

So, create a simple window with a set of icons. Details are described in the comments:

//    JavaFX     Application public class FXUIDemo extends Application { public static void main(String[] args) { //     --    FX       Application.launch(args); } private HBox taskbar; @Override public void start(Stage stage) { //     stage    stage.setTitle("FX Demo"); //    ,      layout manager   BorderPane root = new BorderPane(); Scene scene = new Scene(root, 720, 550, Color.LIGHTGRAY); stage.setScene(scene); //   layout  - -- horizontal box taskbar = new HBox(10); taskbar.setPadding(new Insets(10, 30, 50, 30)); taskbar.setPrefHeight(150); taskbar.setAlignment(Pos.CENTER); root.setBottom(taskbar); //        for (int i = 0; i < 5; i++) { ImageView node = new ImageView(new Image(getClass().getResource("icon-" + i + ".png").toString())); taskbar.getChildren().add(node); } stage.setVisible(true); } } 

Here is the result of this code:

image

Now animate the buttons.

To do this, select their creation in a separate method, add animation while holding the mouse, reflection and animation of pressing the button.

In this case, the animation will be performed by the class ScaleTransition. It looks like this:

 ScaleTransition animationGrow = new ScaleTransition(Duration.valueOf(300), node); animationGrow.setToX(1.3); animationGrow.setToY(1.3); animationGrow.play(); 


In this code, we specify ScaleTransiton, that in 300ms the node object should become 1.3 times the initial one. Nothing more is required; the ScaleTransition class will calculate all intermediate values ​​and apply it to the node object itself. If desired, you can control the smoothness of the change in value, FPS and other parameters.
A set of similar Transition classes is available for animation based on other properties of JavaFX objects: size, location, angle, transparency, etc.

Now add a reflection:

 node.setEffect(new Reflection()); 


We are completely satisfied with the basic settings, so you don’t need to call anything except the effect constructor.
After adding mouse handlers, the createButton () function will look like this:

 private static final double SCALE = 1.3; //   private static final double DURATION = 300; //     private Node createButton(String iconName, final Runnable action) { //   final ImageView node = new ImageView(new Image(getClass().getResource(iconName).toString())); //     final ScaleTransition animationGrow = new ScaleTransition(Duration.valueOf(DURATION), node); animationGrow.setToX(SCALE); animationGrow.setToY(SCALE); //   final ScaleTransition animationShrink = new ScaleTransition(Duration.valueOf(DURATION), node); animationShrink.setToX(1); animationShrink.setToY(1); //    final Reflection effect = new Reflection(); node.setEffect(effect); //    node.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { action.run(); } }); //         node.setOnMouseEntered(new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { node.toFront(); animationShrink.stop(); animationGrow.playFromStart(); } }); //    --    node.setOnMouseExited(new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { animationGrow.stop(); animationShrink.playFromStart(); } }); return node; } 


Now let's add a button click handler. In the Makovsky taskbar, it is then darkened for a short time. We use the ColorAdjust effect and the Timeline class to implement this behavior. Usually, the Timeline is used to solve animation problems that lack Transitions functionality. Using the Timeline, the developer can choose which properties of objects will change over time, setting key points. But for now, we will limit ourselves to using Timeline as a timer to cancel the effect:

 //    final ColorAdjust effectPressed = new ColorAdjustBuilder().brightness(-0.5).build(); node.setOnMouseReleased(new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { //     .    :      , //      ,   input    effect.setInput(effectPressed); //  Timeline,   300   . new TimelineBuilder().keyFrames(new KeyFrame(Duration.valueOf(300), new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { effect.setInput(null); } })).build().play(); action.run(); } }); 


It is worth noting that the Timeline and ColorAdjust were created using the builder template. Similar builders are added for almost all JavaFX2.0 objects, which allows you to write more compact code and avoid using unnecessary variables.

That's what we did. In the image, the cursor is above the fourth button. The screenshot, unfortunately, does not show animations, so, I hope, you will have the opportunity and desire to try it yourself.

image

But we will not stop there. The icons for the buttons were chosen by chance, and then on each button I will add the corresponding JavaFX components.

To begin with, we will add a place on our stage to place new components.

 // StackPane --  layout manager,         StackPane view = new StackPane(); root.setCenter(view); view.getChildren().add(new Text("Hello from JavaFX...")); 


Next, erase the cycle of creating buttons, now we will create them one by one together with informative click handlers.

So, the first button is a media file.

In the body of the start () function, add one line to create the Media Player and call the function createButton () to start it.

 mediaPlayer = new MediaPlayer(new Media("http://webcast-west.sun.com/oow2010.flv")); taskbar.getChildren().add(createButton("icon-0.png", new Runnable() { public void run() { changeView(new MediaView(mediaPlayer)); mediaPlayer.play(); } })); 


To shorten the code of the handlers for pressing subsequent buttons, the function changeView () was added and the variables mediaPlayer and view were rendered.

 private StackPane view; private MediaPlayer mediaPlayer; private void changeView(Node node) { view.getChildren().clear(); //  view mediaPlayer.stop(); //  ,    view.getChildren().add(node); //   view   } 


Get

image

The second button is graphics.

In JavaFX2.0, 6 different types of graphs have been added. You can learn more about them in the ChartsSampler demo application that comes with the SDK.
By clicking on the second button we will create a Line Chart.
This will require a bit more code than for a media player. You need to adjust the coordinate axes, give all elements of the graph names and, of course, create data for the graph.
However, all this fits into 15-20 lines of code.

 taskbar.getChildren().add(createButton("icon-1.png", new Runnable() { public void run() { //   NumberAxis xAxis = new NumberAxis(); NumberAxis yAxis = new NumberAxis(); //  LineChart<Number, Number> chart = new LineChart<Number, Number>(xAxis, yAxis); chart.setTitle("Basic LineChart"); xAxis.setLabel("X Axis"); yAxis.setLabel("Y Axis"); //    XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); series.setName("Random Data"); Random random = new Random(); for (int i = 0; i < 10 + random.nextInt(20); i++) { series.getData().add(new XYChart.Data<Number, Number>(10 * i + 5, random.nextDouble() * 120)); } chart.getData().add(series); changeView(chart); } })); 


image

Although we do not use this, it is worth noting that the graphs are already animated and the addition of new elements will lead to a smooth shift of old data.

On the next button hang another new control with a funny name Accordion. It is a set of sliding panels, a fairly common element of the interface recently.

 taskbar.getChildren().add(createButton("icon-2.png", new Runnable() { public void run() { Accordion accordion = new Accordion(); for (int i = 0; i <= 4; i++) { TitledPane t1 = new TitledPane(new Label("Image " + i), new ImageView(new Image(getClass().getResource("icon-" + i + ".png").toString()))); accordion.getPanes().add(t1); } changeView(accordion); } })); 


In the screenshot, unfortunately, you can’t see the animation again: the panels do not unfold openly, but smoothly and beautifully.

image

The fourth button: WebView - embedded browser. This component provides a full-fledged WebKit-based browser that supports CSS, JavaScript, DOM, and HTML5.

Add

 taskbar.getChildren().add(createButton("icon-3.png", new Runnable() { public void run() { WebView web = new WebView(new WebEngine("http://habrahabr.ru")); changeView(web); } })); 


and see habrahabr.ru inside JavaFX.

image

Finally, for the last, fifth button, I left two other great features of JavaFX2.0 — binding and CSS styles.

Binding allows you to link together the properties of virtually any two JavaFX objects. Developers do not need to worry about creating listeners and synchronization; it’s enough to write one line of code to bind properties. For example, like this:

 Slider slider = new Slider(); Circle circle = new Circle(); circle.radiusProperty().bind(slider.valueProperty()); 


Now, when the slider control slider changes position, the circle radius will automatically change and the circle will be redrawn.
Of course, binding is not limited to banal direct binding. You can create formulas, change data types, apply two-way binding, but this is a topic for a separate article.

Also, each element of the JavaFX scene has styles that can be combined into classes and set in CSS files or set directly.
In the component for the fifth button, we will combine these two functionalities: we will create a component list with different styles and, through binding, connect the style of our taskbar with the selected list item.

 taskbar.getChildren().add(createButton("icon-4.png", new Runnable() { public void run() { //   ListView listView = new ListView(); //    listView.setItems(FXCollections.observableArrayList( "-fx-background-color: green;", "-fx-background-color: linear (0%,0%) to (100%,100%) stops (0.0,aqua) (1.0,red);", "-fx-background-color: transparent;", "-fx-opacity: 0.3;", "-fx-opacity: 1;")); //  binding         taskbar.styleProperty().bind(listView.getSelectionModel().selectedItemProperty()); changeView(listView); } })); 


Here, for example, will look like a taskbar with a gradient in the background.

image

That's all. We wrote less than 200 lines of code and created a pretty cute UI pattern.

In conclusion, several links:
- Application code from the article: http://www.javaone.ru/data/FXUIDemo.zip
- Video with the application in action: http://www.youtube.com/watch?v=IHhA8G-0C9M
- At the address http://download.oracle.com/javafx/ are articles with an overview of the main functionality
- In addition, the SDK and Netbeans bundle include demo applications along with the source code. Especially should be interesting:
- Ensemble - a huge collection of examples with built-in javadoc and code view.
- ChartsSampler - a demonstration of the capabilities of the charts, and quite unusual.

The article was prepared by Sergey Grinev and Alexander Belokrylov.

Source: https://habr.com/ru/post/120457/


All Articles