JavaFX maximize the size of node children - layout

I want to have squares added to a pane, and those squares maximized.
One square takes up the whole pane.
Two squares split the pane.
Three squares make it all in thirds.
When it overflows it goes to the next "row" and continues the process.
All the squares should be the same size.
Is there a way of using the standard layouts or which should I modify?
Thanks

Here's my take on this problem. I don't think it's a great solution, but at least it might help point out some techniques somebody might build on to get a better solution. Basically the solution overrides layoutChildren() to recalculate the preferred tile size as the number of tiles or the available space changes. I'm not sure getWidth or getHeight should really be called from layoutChildren (though it seems to work in this case).
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.Random;
public class TilePaneSample extends Application {
private static final Random random = new Random(42);
#Override
public void start(Stage stage) {
TilePane tiles = createTiles();
VBox layout = new VBox(
createControls(tiles),
tiles
);
VBox.setVgrow(tiles, Priority.ALWAYS);
stage.setScene(new Scene(layout, 400, 300));
stage.show();
}
private TilePane createTiles() {
TilePane tiles = new TilePane() {
#Override
protected void layoutChildren() {
if (getChildren().size() > 0) {
setPrefTileWidth(
Math.floor(
Math.min(
Math.max(
Tile.MIN_SIZE,
getWidth() / getChildren().size()
),
getHeight()
)
)
);
setPrefTileHeight(getPrefTileWidth());
}
super.layoutChildren();
}
};
tiles.setStyle("-fx-background-color: papayawhip;");
tiles.setPrefColumns(5);
tiles.setPrefRows(5);
tiles.getChildren().add(new Tile());
return tiles;
}
private ToolBar createControls(TilePane tiles) {
Button addTile = new Button("Add Tile");
addTile.setOnAction(action -> tiles.getChildren().add(new Tile()));
Button removeTiles = new Button("Remove Tiles");
removeTiles.setOnAction(action -> tiles.getChildren().clear());
ToolBar controls = new ToolBar(addTile, removeTiles);
controls.setMinHeight(ToolBar.USE_PREF_SIZE);
return controls;
}
private class Tile extends StackPane {
public static final int MIN_SIZE = 100;
public Tile() {
setStyle(
"-fx-background-color: " +
"rgb(" + random.nextInt(256) + ", " +
+ random.nextInt(256) + ", "
+ random.nextInt(256) + ");"
);
setMinSize(MIN_SIZE, MIN_SIZE);
}
}
public static void main(String[] args) { launch(args); }
}

Related

Javafx - Cursor intersect shape

I have a few objects on a board and I'd like to get those objects's indexes by the coordinates.
I've tried making a MouseEvent handler and using the getBoundInParent() combined with MouseInfo.getPointerInfo().getLocation(), but unsuccessful. These methods gave me different coordinates and could not match them.
Should I make a rectangle by the cursor's coordinates and use the getBoundInParent().intersects method?
Any advices?
Solution
On each of the shapes, provide setOnMouseEntered and setOnMouseExited handlers to catch the mouse entering and exiting events and record the index of the shape which the mouse is over.
Assumption
I assume you need to intersect the cursor hotspot (e.g. the tip of the mouse pointer arrow) and not the cursor shape or the cursor's rectangular bounds (as intersection of the hotspot is the standard way that cursors work).
Sample Application Output
When you mouse over the circle, the circle will be highlighted and the circle's index (1) will display
When you mouse over the rectangle, the rectangle will be highlighted and the rectangles's index (2) will display.
When you don't mouse over either shape, neither shape will be highlighted and no index will display.
Sample Code
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
public class ShapeIntersector extends Application {
private static final Shape[] shapes = {
new Circle(50, Color.AQUAMARINE),
new Rectangle(100, 100, Color.PALEGREEN)
};
private static final DropShadow highlight =
new DropShadow(20, Color.GOLDENROD);
#Override
public void start(Stage stage) throws Exception {
HBox layout = new HBox(40);
layout.setPadding(new Insets(30));
layout.setAlignment(Pos.CENTER);
Label highlightedShapeLabel = new Label(" ");
highlightedShapeLabel.setStyle(
"-fx-font-family: monospace; -fx-font-size: 80px; -fx-text-fill: olive"
);
for (Shape shape: shapes) {
layout.getChildren().add(shape);
shape.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
shape.setEffect(highlight);
int idx = layout.getChildren().indexOf(shape) + 1;
highlightedShapeLabel.setText(
"" + idx
);
}
});
shape.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
shape.setEffect(null);
highlightedShapeLabel.setText(" ");
}
});
}
layout.getChildren().add(highlightedShapeLabel);
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) { launch(args); }
}

Internal Frames in JavaFX

I found this example of Internal Frames
http://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html
Is it possible to make the same internal Frames in JavaFX?
With JFXtras there is a Window control, where you can add content and handle the internal window behavior.
First you will need to put in your classpath the jfxtras library. They have some instructions where you can get the library. If you are using maven, just need to add:
<dependency>
<groupId>org.jfxtras</groupId>
<artifactId>jfxtras-labs</artifactId>
<version>2.2-r5</version>
</dependency>
Or download the library and put it into your project classpath, whatever.
Now I put a sample of the demo of the Window with a little difference, allowing generation of several windows.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import jfxtras.labs.scene.control.window.CloseIcon;
import jfxtras.labs.scene.control.window.MinimizeIcon;
import jfxtras.labs.scene.control.window.Window;
public class WindowTests extends Application {
private static int counter = 1;
private void init(Stage primaryStage) {
final Group root = new Group();
Button button = new Button("Add more windows");
root.getChildren().addAll(button);
primaryStage.setResizable(false);
primaryStage.setScene(new Scene(root, 600, 500));
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
// create a window with title "My Window"
Window w = new Window("My Window#"+counter);
// set the window position to 10,10 (coordinates inside canvas)
w.setLayoutX(10);
w.setLayoutY(10);
// define the initial window size
w.setPrefSize(300, 200);
// either to the left
w.getLeftIcons().add(new CloseIcon(w));
// .. or to the right
w.getRightIcons().add(new MinimizeIcon(w));
// add some content
w.getContentPane().getChildren().add(new Label("Content... \nof the window#"+counter++));
// add the window to the canvas
root.getChildren().add(w);
}
});
}
public double getSampleWidth() {return 600;}
public double getSampleHeight() {return 500;}
#Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) {launch(args);}
}
In the original demo, the event code was in the init method, and no button was included. I add the button to create dynamically windows and adding them to the screen.
Here is a snapshot of the result of the application:
I totally recommend you try the demo of jfxtras. They have really great stuff. Hope it helps.
You can implement simple internal window themselves. Main idea, that InternalWindow class just skeleton, that has internal frame like functionality. You can apply any content to it.
1) Declare class
public class InternalWindow extends Region
2) You should be able to set content in window
public void setRoot(Node node) {
getChildren().add(node);
}
3) You should be able to bring window to front if many window exist
public void makeFocusable() {
this.setOnMouseClicked(mouseEvent -> {
toFront();
});
}
4) Now we need dragging functionality
//just for encapsulation
private static class Delta {
double x, y;
}
//we can select nodes that react drag event
public void makeDragable(Node what) {
final Delta dragDelta = new Delta();
what.setOnMousePressed(mouseEvent -> {
dragDelta.x = getLayoutX() - mouseEvent.getScreenX();
dragDelta.y = getLayoutY() - mouseEvent.getScreenY();
//also bring to front when moving
toFront();
});
what.setOnMouseDragged(mouseEvent -> {
setLayoutX(mouseEvent.getScreenX() + dragDelta.x);
setLayoutY(mouseEvent.getScreenY() + dragDelta.y);
});
}
5) Also we want able to resize window (I show only simple right-bottom resizing)
//current state
private boolean RESIZE_BOTTOM;
private boolean RESIZE_RIGHT;
public void makeResizable(double mouseBorderWidth) {
this.setOnMouseMoved(mouseEvent -> {
//local window's coordiantes
double mouseX = mouseEvent.getX();
double mouseY = mouseEvent.getY();
//window size
double width = this.boundsInLocalProperty().get().getWidth();
double height = this.boundsInLocalProperty().get().getHeight();
//if we on the edge, change state and cursor
if (Math.abs(mouseX - width) < mouseBorderWidth
&& Math.abs(mouseY - height) < mouseBorderWidth) {
RESIZE_RIGHT = true;
RESIZE_BOTTOM = true;
this.setCursor(Cursor.NW_RESIZE);
} else {
RESIZE_BOTTOM = false;
RESIZE_RIGHT = false;
this.setCursor(Cursor.DEFAULT);
}
});
this.setOnMouseDragged(mouseEvent -> {
//resize root
Region region = (Region) getChildren().get(0);
//resize logic depends on state
if (RESIZE_BOTTOM && RESIZE_RIGHT) {
region.setPrefSize(mouseEvent.getX(), mouseEvent.getY());
} else if (RESIZE_RIGHT) {
region.setPrefWidth(mouseEvent.getX());
} else if (RESIZE_BOTTOM) {
region.setPrefHeight(mouseEvent.getY());
}
});
}
6) Usage. First we construct all layout. Then apply it to InternalWindow.
private InternalWindow constructWindow() {
// content
ImageView imageView = new ImageView("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Cheetah4.jpg/250px-Cheetah4.jpg");
// title bar
BorderPane titleBar = new BorderPane();
titleBar.setStyle("-fx-background-color: green; -fx-padding: 3");
Label label = new Label("header");
titleBar.setLeft(label);
Button closeButton = new Button("x");
titleBar.setRight(closeButton);
// title bat + content
BorderPane windowPane = new BorderPane();
windowPane.setStyle("-fx-border-width: 1; -fx-border-color: black");
windowPane.setTop(titleBar);
windowPane.setCenter(imageView);
//apply layout to InternalWindow
InternalWindow interalWindow = new InternalWindow();
interalWindow.setRoot(windowPane);
//drag only by title
interalWindow.makeDragable(titleBar);
interalWindow.makeDragable(label);
interalWindow.makeResizable(20);
interalWindow.makeFocusable();
return interalWindow;
}
7) And how add window to layout
#Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
root.getChildren().add(constructWindow());
root.getChildren().add(constructWindow());
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
Result
Full code: gist
Upd about close button:
You can add method to InternalWindow
public void setCloseButton(Button btn) {
btn.setOnAction(event -> ((Pane) getParent()).getChildren().remove(this));
}
And when construct:
interalWindow.setCloseButton(closeButton);

Water 2D wave effect in JavaFX

how can I implement water 2D wave effect in JavaFX, I have image and want to when click on image a wave(or more) start expanding from that point, just like when we drop a piece rock into the calm water and we see the wave expanding.
This is a conversion of parts of old sun JavaFX 1 ripple generator to JavaFX 2.
It's not the most realistic water ripple effect, but maybe it's enough to get you started creating your own. You could add in a DisplacementMap effect to distort your image as a result of the "waves".
The code uses JavaFX animation timelines to generate expanding concentric circles that gradually fade away of time.
import javafx.animation.*;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.collections.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.*;
import javafx.scene.shape.Circle;
import javafx.stage.*;
import javafx.util.Duration;
public class FishSim extends Application {
private static final Paint SCENE_FILL = new RadialGradient(
0, 0, 300, 300, 500, false, CycleMethod.NO_CYCLE,
FXCollections.observableArrayList(new Stop(0, Color.BLACK), new Stop(1, Color.BLUE))
);
#Override public void start(Stage stage) {
final RippleGenerator rippler = new RippleGenerator();
final Scene scene = new Scene(rippler, 600, 400, SCENE_FILL);
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
rippler.setGeneratorCenterX(event.getSceneX());
rippler.setGeneratorCenterY(event.getSceneY());
rippler.createRipple();
rippler.startGenerating();
}
});
scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
rippler.setGeneratorCenterX(event.getSceneX());
rippler.setGeneratorCenterY(event.getSceneY());
}
});
scene.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
rippler.stopGenerating();
}
});
stage.setTitle("Click, hold mouse button down and move around to create ripples");
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) { launch(args); }
}
/**
* Generates ripples on the screen every 0.5 seconds or whenever
* the createRipple method is called. Ripples grow and fade out
* over 3 seconds
*/
class RippleGenerator extends Group {
private class Ripple extends Circle {
Timeline animation = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(radiusProperty(), 0)),
new KeyFrame(Duration.seconds(1), new KeyValue(opacityProperty(), 1)),
new KeyFrame(Duration.seconds(3), new KeyValue(radiusProperty(), 100)),
new KeyFrame(Duration.seconds(3), new KeyValue(opacityProperty(), 0))
);
private Ripple(double centerX, double centerY) {
super(centerX, centerY, 0, null);
setStroke(Color.rgb(200, 200, 255));
}
}
private double generatorCenterX = 100.0;
private double generatorCenterY = 100.0;
private Timeline generate = new Timeline(
new KeyFrame(Duration.seconds(0.5), new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
createRipple();
}
}
)
);
public RippleGenerator() {
generate.setCycleCount(Timeline.INDEFINITE);
}
public void createRipple() {
final Ripple ripple = new Ripple(generatorCenterX, generatorCenterY);
getChildren().add(ripple);
ripple.animation.play();
Timeline remover = new Timeline(
new KeyFrame(Duration.seconds(3), new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
getChildren().remove(ripple);
ripple.animation.stop();
}
})
);
remover.play();
}
public void startGenerating() {
generate.play();
}
public void stopGenerating() {
generate.stop();
}
public void setGeneratorCenterX(double generatorCenterX) {
this.generatorCenterX = generatorCenterX;
}
public void setGeneratorCenterY(double generatorCenterY) {
this.generatorCenterY = generatorCenterY;
}
}
The original JavaFX 1 fish simulator code that the conversion is based on came from a jfrog repository (which might no longer exist if you click it).
Robert Ladstätter created a 2D water effect sample animation for JavaFX 2 (using Scala). Roberts animation is like viewing the water from the side rather than above, but perhaps some of the concepts might help you.
In this tutorial you can find how to use custom GLSL/HLSL pixel shaders for JavaFX.
And the code for a simple distortion procedural wave in screenSpace in HLSL form:
uniform extern texture ScreenTexture;
sampler ScreenS = sampler_state
{
Texture = <ScreenTexture>;
};
float wave; // pi/.75 is a good default
float distortion; // 1 is a good default
float2 centerCoord; // 0.5,0.5 is the screen center
float4 PixelShader(float2 texCoord: TEXCOORD0) : COLOR
{
float2 distance = abs(texCoord - centerCoord);
float scalar = length(distance);
// invert the scale so 1 is centerpoint
scalar = abs(1 - scalar);
// calculate how far to distort for this pixel
float sinoffset = sin(wave / scalar);
sinoffset = clamp(sinoffset, 0, 1);
// calculate which direction to distort
float sinsign = cos(wave / scalar);
// reduce the distortion effect
sinoffset = sinoffset * distortion/32;
// pick a pixel on the screen for this pixel, based on
// the calculated offset and direction
float4 color = tex2D(ScreenS, texCoord+(sinoffset*sinsign));
return color;
}
technique
{
pass P0
{
PixelShader = compile ps_2_0 PixelShader();
}
}
I hope it helps.

JavaFX ProgressBar: how to change bar color?

I'm trying to change the color of bar in ProgressBar with
pBar.setStyle("-fx-accent: green");
but I have encountered a problem: that doesn't seem to work right for me! (Or I just don't understand something)
here is the code:
public class JavaFXApplication36 extends Application {
#Override
public void start(Stage primaryStage) {
AnchorPane root = new AnchorPane();
ProgressBar pbRed = new ProgressBar(0.4);
ProgressBar pbGreen = new ProgressBar(0.6);
pbRed.setLayoutY(10);
pbGreen.setLayoutY(30);
pbRed.setStyle("-fx-accent: red;"); // line (1)
pbGreen.setStyle("-fx-accent: green;"); // line (2)
root.getChildren().addAll(pbRed, pbGreen);
Scene scene = new Scene(root, 150, 50);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I always get 2 red progressbars with it! It seems that code in line (1) changes the style of ProgressBar class, not the instance.
Another strange moment is that deleting line (1) don't result in 2 green progress bars. So I can figure that line (2) is completely useless!! WHY?! That's definitely getting odd.
Is there any way to set separate colors for separate progressbars?
Answer updated to add a simple non-animated example with multiple progress bars
The code in your question should display two different colored progress bars, the fact that it doesn't is a bug in the JavaFX css processing system. Log the bug against the runtime project here: http://javafx-jira.kenai.com.
As a workaround, instead of calling setStyle on the progress bars, define the accent colors used to color progress bars within a stylesheet and add a style class to the progress bars. Then, you can create multiple progress bars within the same application, all with different colors.
As Uluk points out, you can use JavaFX 2.2 caspian.css in conjunction with the JavaFX 2 css reference guide and the JavaFX 2 css tutorial to determine how to style things.
Here is some sample code which customizes a progress bar based upon the information in those references.
Sample css:
/** progress.css
place in same directory as
ColoredProgressBarStyleSheet.java or SimpleColoredProgressBar.java
ensure build system copies the css file to the build output path */
.root { -fx-background-color: cornsilk; -fx-padding: 15; }
.progress-bar { -fx-box-border: goldenrod; }
.green-bar { -fx-accent: green; }
.yellow-bar { -fx-accent: yellow; }
.orange-bar { -fx-accent: orange; }
.red-bar { -fx-accent: red; }
Simple sample program:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
// shows multiple progress bars drawn in different colors.
public class SimpleColoredProgressBar extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final VBox layout = new VBox(10);
layout.setAlignment(Pos.CENTER);
layout.getChildren().setAll(
new ColoredProgressBar("red-bar", 0.2),
new ColoredProgressBar("orange-bar", 0.4),
new ColoredProgressBar("yellow-bar", 0.6),
new ColoredProgressBar("green-bar", 0.8)
);
layout.getStylesheets().add(getClass().getResource("progress.css").toExternalForm());
stage.setScene(new Scene(layout));
stage.show();
}
class ColoredProgressBar extends ProgressBar {
ColoredProgressBar(String styleClass, double progress) {
super(progress);
getStyleClass().add(styleClass);
}
}
}
Simple sample program output:
More complicated sample program with a single animated progress bar which changes color dynamically depending on the amount of progress made:
import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
// shows a progress bar whose bar changes color depending on the amount of progress.
public class ColoredProgressBarStyleSheet extends Application {
public static void main(String[] args) { launch(args); }
private static final String RED_BAR = "red-bar";
private static final String YELLOW_BAR = "yellow-bar";
private static final String ORANGE_BAR = "orange-bar";
private static final String GREEN_BAR = "green-bar";
private static final String[] barColorStyleClasses = { RED_BAR, ORANGE_BAR, YELLOW_BAR, GREEN_BAR };
#Override public void start(Stage stage) {
final ProgressBar bar = new ProgressBar();
final Timeline timeline = new Timeline(
new KeyFrame(Duration.millis(0), new KeyValue(bar.progressProperty(), 0)),
new KeyFrame(Duration.millis(3000), new KeyValue(bar.progressProperty(), 1))
);
Button reset = new Button("Reset");
reset.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
timeline.playFromStart();
}
});
bar.progressProperty().addListener(new ChangeListener<Number>() {
#Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
double progress = newValue == null ? 0 : newValue.doubleValue();
if (progress < 0.2) {
setBarStyleClass(bar, RED_BAR);
} else if (progress < 0.4) {
setBarStyleClass(bar, ORANGE_BAR);
} else if (progress < 0.6) {
setBarStyleClass(bar, YELLOW_BAR);
} else {
setBarStyleClass(bar, GREEN_BAR);
}
}
private void setBarStyleClass(ProgressBar bar, String barStyleClass) {
bar.getStyleClass().removeAll(barColorStyleClasses);
bar.getStyleClass().add(barStyleClass);
}
});
final VBox layout = new VBox(10);
layout.setAlignment(Pos.CENTER);
layout.getChildren().setAll(bar, reset);
layout.getStylesheets().add(getClass().getResource("progress.css").toExternalForm());
stage.setScene(new Scene(layout));
stage.show();
timeline.play();
}
}
More complicated sample program output:
You should to override (or customize) the style with JavaFX CSS selectors. See caspian.css for more information. In your own stylesheet define:
.progress-bar .bar {
-fx-background-color:
-fx-box-border,
linear-gradient(to bottom, derive(-fx-accent,95%), derive(-fx-accent,10%)),
red; /* this line is the background color of the bar */
-fx-background-insets: 0, 1, 2;
-fx-padding: 0.416667em; /* 5 */
}
For those who want a simple answer (and without needing to add CSS files):
ProgressBar pbGreen = new ProgressBar(0.6);
pbGreen.setStyle("-fx-accent: green");

How to make an undecorated window movable / draggable in JavaFX?

I have to create an application in which minimize and maximize button will be disabled.
I have used "StageStyle.UNDECORATED" with which the application will not be movable or draggable anymore, so I am searching for any other alternative to make my application.
Do anyone having solution for this?
To achieve the window to be undecorated but still movable/dragable you have to handle the appropriate MouseEvent on any node of your choice.
Example:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class SimpleWindowApplication extends Application {
private double xOffset = 0;
private double yOffset = 0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(final Stage primaryStage) {
primaryStage.initStyle(StageStyle.UNDECORATED);
BorderPane root = new BorderPane();
root.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
xOffset = event.getSceneX();
yOffset = event.getSceneY();
}
});
root.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
primaryStage.setX(event.getScreenX() - xOffset);
primaryStage.setY(event.getScreenY() - yOffset);
}
});
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Learn more from the very valuable examples contained on Oracle's JavaFX download page under: JavaFX Demos and Samples
Sole purpose of this class is to allow undecorated Window to be dragged. It also performs the duty to ensure TaskBar remains visible with FullScreen, and ensure undecorated window not dragged out of screen.
Lastly its provides a bug fix to the error "css resource not found."
Simply paste below code in the main class in the overridden start() method just about when the Stage is ABOUT READY to be shown or after.
WindowStyle.allowDrag(root, stage);
WindowStyle.stageDimension(stage.getWidth(), stage.getHeight());
NOTE: Paste the above when the Stage is ABOUT READY to be shown or after.
For full screen window use:
WindowStyle.fullScreen(Stage stage);
To resize back to previous use:
WindowStyle.restoreScreen(Stage stage);
To add custom stylesheets to your scene, Simply paste below code in the main class in the overridden start() method after defining your scene.
scene.getStylesheets().add(WindowStyle.addStyleSheet(String css));
The name of css to be used for styling can be in the form of: main.css or styles/main.css
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Screen;
import javafx.stage.Stage;
/**
* #author: BENJAH
*/
public class WindowStyle {
private static final Rectangle2D SCREEN_BOUNDS= Screen.getPrimary()
.getVisualBounds();
private static double[] pref_WH, offset_XY;
private static String styleSheet;
private WindowStyle(String css) {
styleSheet= getClass().getResource(css).toString();
}
protected static void allowDrag(Parent root, Stage stage) {
root.setOnMousePressed((MouseEvent p) -> {
offset_XY= new double[]{p.getSceneX(), p.getSceneY()};
});
root.setOnMouseDragged((MouseEvent d) -> {
//Ensures the stage is not dragged past the taskbar
if (d.getScreenY()<(SCREEN_BOUNDS.getMaxY()-20))
stage.setY(d.getScreenY() - offset_XY[1]);
stage.setX(d.getScreenX() - offset_XY[0]);
});
root.setOnMouseReleased((MouseEvent r)-> {
//Ensures the stage is not dragged past top of screen
if (stage.getY()<0.0) stage.setY(0.0);
});
}
//Sets the default stage prefered width and height.
protected static void stageDimension(Double width, Double height) {
pref_WH= new double[]{width, height};
}
protected static void fullScreen(Stage stage) {
stage.setX(SCREEN_BOUNDS.getMinX());
stage.setY(SCREEN_BOUNDS.getMinY());
stage.setWidth(SCREEN_BOUNDS.getWidth());
stage.setHeight(SCREEN_BOUNDS.getHeight());
}
protected static void restoreScreen(Stage stage) {
stage.setX((SCREEN_BOUNDS.getMaxX() - pref_WH[0])/2);
stage.setY((SCREEN_BOUNDS.getMaxY() - pref_WH[1])/2);
stage.setWidth(pref_WH[0]);
stage.setHeight(pref_WH[1]);
}
protected static String addStyleSheet(String css) {
new WindowStyle(css);
return styleSheet;
}
}

Resources