Basically, i want to display tooltip with some extra information when I hover over one of the peaks.
However, I can't guess how to get that peak's location on monitor (because tooltip asks for absolute coordinates of your monitor)
This is my current code
//dateNumberData is the peak
Tooltip tooltip = new Tooltip();
//Here i just edit tooltip info
dateNumberData.getNode().setOnMouseEntered(event -> {
tooltip.show(dateNumberData.getNode(),
dateNumberData.getNode().localToScreen(dateNumberData.getNode().getLayoutX(), 0).getX(),
dateNumberData.getNode().localToScreen(0, dateNumberData.getNode().getLayoutY()).getY());
});
dateNumberData.getNode().setOnMouseExited(event -> tooltip.hide());
But tooltip appears all over the place. If I use dateNumberData.getNode().getParent().localToScreen() tooltip just doesn't appear at all (but tooltip.getX() returns kinda correct coordinates. At least it shoudld appear with those coordinates)
The layoutX() and layoutY() properties are not the correct ones to use here. Those might be the coordinates of the node in the parent, though you don't know that the node is positioned by setting those: e.g. it might use a translation or some other layout mechanism. Instead use getBoundsInLocal() and then transform the bounds.
It's also a good idea to add a small offset to the tooltip: this not only looks better, but it prevents the tooltip obscuring the node, which means you trigger mouse exited, and end up in a repeating loop.
dateNumberData.getNode().setOnMouseEntered(event -> {
Bounds bounds = dateNumberData.getNode().localToScreen(dateNumberData.getNode().getBoundsInLocal());
tooltip.show(dateNumberData.getNode(),
bounds.getMaxX()+15,
bounds.getMaxY()+5);
});
Here is an SSCCE:
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class LineChartWithTooltip extends Application {
#Override
public void start(Stage primaryStage) {
LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis());
Series<Number, Number> series = new Series<>();
series.setName("Data");
Random rng = new Random();
for (int i = 0 ; i <= 10; i++) {
series.getData().add(new Data<>(i, rng.nextDouble()));
}
chart.getData().add(series);
Tooltip tooltip = new Tooltip();
for (Data<Number, Number> d : series.getData()) {
d.getNode().setOnMouseEntered(event -> {
tooltip.setText(String.format("[%d, %.3f]", d.getXValue().intValue(), d.getYValue().doubleValue()));
Bounds nodeBounds = d.getNode().getBoundsInLocal();
Bounds nodeBoundsInScreen = d.getNode().localToScreen(nodeBounds);
tooltip.show(d.getNode(),
nodeBoundsInScreen.getMaxX()+15,
nodeBoundsInScreen.getMaxY()+5);
});
d.getNode().setOnMouseExited(event -> tooltip.hide());
}
primaryStage.setScene(new Scene(new BorderPane(chart), 600, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Related
I am using PopOver from ControlsFX, in a TableView If I trigger the startEdit of a cell, it should pop the PopOver. This part it works, the problem is, the arrow which is pointing to the row is not on the right place every time. If I select a row from the table which is at the bottom of the table , it points to a cell above it.
I need that arrow to point every time to the right cell in the TableView.
ControlsFX , version: 8.40.14
How can I solve this?
Here is the code where you can see how it works:
package stackoverflow.popover;
import com.sun.deploy.util.StringUtils;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.controlsfx.control.PopOver;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class Controller implements Initializable {
#FXML
private TableView<Model> table;
#FXML
private TableColumn<Model, ObservableList<String>> listCell;
#Override
public void initialize(URL location, ResourceBundle resources) {
Model model = new Model(FXCollections.observableArrayList("Apple", "Peach"));
ObservableList<Model> items = FXCollections.observableArrayList();
for (int i = 0; i < 50; i++) {
items.add(model);
}
table.setItems(items);
table.setEditable(true);
listCell.setCellFactory(factory -> new ListTableCell(
FXCollections.observableArrayList("Apple", "Orange", "Peach", "Banana", "Lemon", "Lime")));
listCell.setCellValueFactory(data -> data.getValue().list);
}
private class ListTableCell extends TableCell<Model, ObservableList<String>> {
private ObservableList<String> allItems;
ListTableCell(ObservableList<String> allItems) {
this.allItems = allItems;
}
#Override
public void startEdit() {
super.startEdit();
PopOver popOver = new PopOver();
popOver.setAutoHide(true);
PopupController sc = new PopupController(allItems, new ArrayList<>(getItem()));
popOver.setContentNode(new StackPane(sc.getPane()));
popOver.setOnHiding(event -> commitEdit(sc.getItems()));
popOver.show(this);
}
#Override
protected void updateItem(ObservableList<String> item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(StringUtils.join(item, ","));
}
}
}
private class Model {
ListProperty<String> list;
public Model(ObservableList<String> list) {
this.list = new SimpleListProperty<>(list);
}
}
private class PopupController {
private BorderPane pane = new BorderPane();
private ListView<String> left = new ListView<>();
private ListView<String> right = new ListView<>();
private Button toLeft = new Button("<");
private Button toRight = new Button(">");
PopupController(List<String> all, List<String> selected) {
VBox leftBox = new VBox();
leftBox.setSpacing(5);
leftBox.getChildren().add(toRight);
leftBox.getChildren().add(left);
pane.setLeft(leftBox);
VBox rightBox = new VBox();
rightBox.setSpacing(5);
rightBox.getChildren().add(toLeft);
rightBox.getChildren().add(right);
pane.setRight(rightBox);
ObservableList<String> allItems = FXCollections.observableArrayList(all);
allItems.removeAll(selected);
left.setItems(allItems);
right.setItems(FXCollections.observableArrayList(selected));
toLeft.disableProperty().bind(right.getSelectionModel().selectedItemProperty().isNull());
toRight.disableProperty().bind(left.getSelectionModel().selectedItemProperty().isNull());
toLeft.setOnAction(event -> {
String str = right.getSelectionModel().getSelectedItem();
right.getItems().remove(str);
left.getItems().add(str);
});
toRight.setOnAction(event -> {
String str = left.getSelectionModel().getSelectedItem();
left.getItems().remove(str);
right.getItems().add(str);
});
}
BorderPane getPane() {
return pane;
}
ObservableList<String> getItems() {
return right.getItems();
}
}
}
Here are two screenshots to show what I mean :
This is even worst: (with setAutoFix(false))
I am not expert with ControlFX but I believe the problem you are facing its because the height of your PopOver is greater than your current screen size thus it is trying to relocate itself in a way to be inside the screen local bounds. So in order to achieve what you are trying you will need to manually set the ArrowLocation of your PopOver control. Here is how you can solve the issue (using your code) :
#Override
public void startEdit() {
super.startEdit();
PopOver popOver = new PopOver();
popOver.setAutoHide(true);
// first set auto fix to false
// to manually set the arrow location
popOver.setAutoFix(false);
PopupController sc = new PopupController(allItems, new ArrayList<>(getItem()));
// set a specific height for our pane
final double paneHeight = 300;
StackPane popOverPane = new StackPane(sc.getPane());
popOverPane.setPrefHeight(paneHeight);
popOver.setContentNode(popOverPane);
popOver.setOnHiding(event -> commitEdit(sc.getItems()));
// find coordinates relative to the screen
Bounds screenBounds = this.localToScreen(this.getBoundsInLocal());
// get our current y position ( on screen )
int yPos = (int) screenBounds.getMinY();
// get screen size
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
int screenHeight = (int) primaryScreenBounds.getHeight();
// if the PopOver height + the current position is greater than
// the max screen's height then set the arrow position to bottom left
if(screenHeight < yPos + paneHeight) {
popOver.setArrowLocation(ArrowLocation.LEFT_BOTTOM);
}
popOver.show(this);
}
Using the code above you would see some things you need to change and think more carefully.
The first one is that you will need to set a specific size for your StackPane or to find a dynamic way to calculate it.
Secondly in my example I am using the Screen.getPrimary() which will get the Rectangle2D dimensions of your primary screen and not the screen you have your application, this means that if you have more monitors with different resolution and your program is displayed on the second one, the code above will still use the first ( default ) monitor's resolution which might not match with the primary one, so you will have to find a way to get the correct monitor resolution.
Lastly you will need to do the same when the window is on the right side of the screen because then the width of the 'Popover' will exceed the width of your monitor
Try setting setAutoFix(false) on the PopOver instance. From the documentation of the autoFix property of the PopOver's superclass PopupWindow:
This convenience variable indicates whether, when the popup is shown,
it should automatically correct its position such that it doesn't end
up positioned off the screen.
I'm working on a simple app and it features a pie chart. My goal is that if a user hovers their mouse over any section of the chart, it will expand and present more information. In my program, the chart is made of 3 arcs. Here's my code.
import javafx.scene.Group; //Maybe too many imports, I just use em all
import javafx.scene.Scene; //because I'm lazy
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Rectangle;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.application.Application;
import javafx.scene.shape.*;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.input.MouseEvent;
import javafx.animation.ScaleTransition;
import java.lang.Thread;
public class AnimatingDemo extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
//create 3 arc variables
Arc arc1 = new Arc();
Arc arc2 = new Arc();
Arc arc3 = new Arc();
//set up arc1 in place and to right color
arc1.setFill(Color.rgb(35,25,43,1.0));
arc1.setCenterX(250);
arc1.setCenterY(250);
arc1.setRadiusX(100.0f);
arc1.setRadiusY(100.0f);
arc1.setStartAngle(315);
arc1.setLength(-90);
arc1.setType(ArcType.ROUND);
//set up and color arc2
arc2.setFill(Color.rgb(39,70,144,1.0));
arc2.setCenterX(250);
arc2.setCenterY(250);
arc2.setRadiusX(100.0f);
arc2.setRadiusY(100.0f);
arc2.setStartAngle(90);
arc2.setLength(-135);
arc2.setType(ArcType.ROUND);
//set up and color arc3
arc3.setFill(Color.rgb(54,65,86,1.0));
arc3.setCenterX(250);
arc3.setCenterY(250);
arc3.setRadiusX(100.0f);
arc3.setRadiusY(100.0f);
arc3.setStartAngle(225);
arc3.setLength(-135);
arc3.setType(ArcType.ROUND);
//create root group
Group root = new Group();
//set up window
//add nodes to root
root.getChildren().addAll(arc1,arc2,arc3);
Scene scene = new Scene(root, 500,500);
stage.setTitle("Testing arc animation");
stage.setScene(scene);
stage.show();
}
}
This is just a sample I made so I can recreate the problem, but it gets the point across. I did research about various methods of animation in Javafx. The animation class seemed most viable, so I tried it in my program. I used the following code:
arc1.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
ScaleTransition st = new ScaleTransition(Duration.millis(1500),arc1);
st.setByX(0.3);
st.setByY(0.3);
st.setCycleCount(1);
st.setAutoReverse(false);
st.play();
}
});
I repeated it 3 times for each arc but that's redundant here.
Anyway, the result is that both ends of the arc scale, so the pi chart looks messy and isn't centered anymore, also the scaling increases depending on the size of the arc so it's inconsistent.
I then decided to move onto a more basic method, using thread.sleep().
arc1.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
for(int a = 0; a < 10; a++) {
try {
arc1.setRadiusX(arc1.getRadiusX() + 1);
arc1.setRadiusY(arc1.getRadiusY() + 1);
Thread.sleep(100);
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
});
this doesn't work either, the circle just instantly expands by the given amount of units I wanted (instantly).
So my question is, what can I do? Is there a method to prevent the skewing in the animation class? Can I make the thread.sleep animation fluent in some way? Any advice helps, thank you for your time!
P.S. If it needs more comments let me know
I'm not sure this is exactly what you are looking for, since you went with Arc's instead of a proper PieChart, but I used the PieChart class and did everything you did and it works out just fine.
Here I took the PieChart.Data class and made three separate ones just for testing.
I added an EventFilter by calling .getNode() on the PieChart.Data variable, and then just pasted your method you supplied above.
Again, I assume there was a reason you used Arc instead of PieChart, but I got it to work this way.
#Override
public void start(Stage stage) {
ObservableList<PieChart.Data> data = FXCollections.observableArrayList();
PieChart pieChart = new PieChart(data);
PieChart.Data one = new PieChart.Data("one", 50.0);
PieChart.Data two = new PieChart.Data("two", 33.0);
PieChart.Data three = new PieChart.Data("three", 17.0);
data.addAll(one, two, three);
one.getNode().addEventFilter(MouseEvent.MOUSE_PRESSED, mouseEvent -> {
ScaleTransition st = new ScaleTransition(Duration.millis(1500),one.getNode());
st.setByX(0.3);
st.setByY(0.3);
st.setCycleCount(1);
st.setAutoReverse(false);
st.play();
});
two.getNode().addEventFilter(MouseEvent.MOUSE_PRESSED, mouseEvent -> {
ScaleTransition st = new ScaleTransition(Duration.millis(1500),two.getNode());
st.setByX(0.3);
st.setByY(0.3);
st.setCycleCount(1);
st.setAutoReverse(false);
st.play();
});
three.getNode().addEventFilter(MouseEvent.MOUSE_PRESSED, mouseEvent -> {
ScaleTransition st = new ScaleTransition(Duration.millis(1500),three.getNode());
st.setByX(0.3);
st.setByY(0.3);
st.setCycleCount(1);
st.setAutoReverse(false);
st.play();
});
//create root group
Group root = new Group();
//set up window
//add nodes to root
root.getChildren().addAll(pieChart);
Scene scene = new Scene(root, 500,500);
stage.setTitle("Testing arc animation");
stage.setScene(scene);
stage.show();
}
I just want to find out if there is any simple way of animating layouts in JavaFx, such as the VBox and HBox. I would like my application to change the background color of my VBox after a specified time. But I realized that there is nothing similar to FillTransition that I could use to do this using a VBox or an HBox. Any advice on how I could do this?
Color transition is very easy with the 2.0-SNAPSHOT version of ReactFX:
ObjectProperty<Color> color = new SimpleObjectProperty<>(Color.WHITE);
Val<Background> animBgr = Val.animate(color, Duration.ofMillis(500))
.map(c -> new Background(new BackgroundFill(c, null, null)));
vbox.backgroundProperty().bind(animBgr);
Now whenever you update color, the background color of vbox will smoothly transition to the new color in 500 milliseconds.
If you want to change color every 5 seconds, you can create an EventStream of colors that emits a color every 5 seconds and use that color to set the value of color:
private static final Color[] COLORS = new Color[] {
Color.WHITE, Color.AQUA, Color.web("#FFDA8F"), Color.CORAL, Color.CYAN
};
private EventStream<Color> colorStream() {
return EventStreams.ticks(Duration.ofSeconds(5))
.accumulate(0, (n, t) -> (n + 1) % COLORS.length)
.map(i -> COLORS[i]);
}
colorStream().feedTo(color);
A full runnable demo looks like this:
import java.time.Duration;
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.value.Val;
public class ChangingBackgroundColor extends Application {
public static void main(String[] args) {
launch(args);
}
private static final Color[] COLORS = new Color[] {
Color.WHITE, Color.AQUA, Color.web("#FFDA8F"), Color.CORAL, Color.CYAN
};
#Override
public void start(Stage stage) throws Exception {
VBox vbox = new VBox();
ObjectProperty<Color> color = new SimpleObjectProperty<>(COLORS[0]);
Val<Background> animBgr = Val.animate(color, Duration.ofMillis(500))
.map(c -> new Background(new BackgroundFill(c, null, null)));
vbox.backgroundProperty().bind(animBgr);
colorStream().feedTo(color);
stage.setScene(new Scene(vbox, 400, 400));
stage.show();
}
private EventStream<Color> colorStream() {
return EventStreams.ticks(Duration.ofSeconds(5))
.accumulate(0, (n, t) -> (n + 1) % COLORS.length)
.map(i -> COLORS[i]);
}
}
Stopping the animation. If the VBox is removed from the scene before the application exits, the animation should be stopped in order to prevent memory and CPU leaks. The feedTo method above returns a Subcription, which I ignored in the sample code above. In order to stop the animation, you would do:
Subscription subscription = colorStream().feedTo(color);
// later
subscription.unsubscribe();
I'm struggling with making an animation showing the searchin in Binary Search Tree in JavaFX.
The goal is to make a visualization of comparing the value of tree node with possibility to:
pause and play it any time
being able to play the animation backwards (to go at least one step back),
give a user an ability to play the animation step-by-step or whole at once.
The preview of visualization
My vision was to make a series of TranslateTransitions(TT) added in one SequentialTransition(ST). If the animation is marked as "step-by-step" the each TT pauses the whole ST in their OnFinished handler. However this kinda works only for going one-way.
My question is. What is the best approach to maintain going fluent and step-by-step animation in reverse direction ?
I was thinking about:
maybe making another sequence of inverse transitions (but how to tell
it from which step to continue ?)
somehow work with rate property ? is it possible to change it while the ST is running ?
Thank you very much for your answers.
In general, you can change the rate property of an Animation while it is in progress. The idea of using a SequentialTransition is appealing, but it doesn't work as easily as you might think. The problem arises when the sequential transition is paused at the boundary between two individual transitions: you don't have any way to tell which of the individual transitions is considered the current one (i.e. the next one or the previous one). So when you try to reverse the rate and play, the sequential transition can get confused and immediately think it's at the end of the one it's trying to play.
You might be able to hack this a little by using Animation.getCurrentTime() and Animation.jumpTo(...) to "nudge" the sequential transition a tiny amount in the correct direction before starting to play any step, but I think it's probably easier just to manage the individual transitions on their own instead of using a SequentialTransition.
Here's a simple example of using this technique to move a rectangle around:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javafx.animation.Animation;
import javafx.animation.Animation.Status;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ReverseSequentialTransitionTest extends Application {
#Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Rectangle rect = new Rectangle(50, 50, 250, 150);
rect.setFill(Color.color(.5, .5, .1));
pane.getChildren().add(rect);
TranslateTransition ttForward = new TranslateTransition(Duration.seconds(1), rect);
ttForward.setFromX(0);
ttForward.setToX(400);
TranslateTransition ttDown = new TranslateTransition(Duration.seconds(1), rect);
ttDown.setFromY(0);
ttDown.setToY(100);
TranslateTransition ttBackward = new TranslateTransition(Duration.seconds(1), rect);
ttBackward.setFromX(400);
ttBackward.setToX(0);
TranslateTransition ttUp = new TranslateTransition(Duration.seconds(1), rect);
ttUp.setFromY(100);
ttUp.setToY(0);
List<Animation> transitions = Arrays.asList(ttForward, ttDown, ttBackward, ttUp);
IntegerProperty nextTransitionIndex = new SimpleIntegerProperty();
Button playButton = new Button("Play Forward");
playButton.setOnAction(event -> {
int index = nextTransitionIndex.get();
Animation anim = transitions.get(index);
anim.setOnFinished(evt -> nextTransitionIndex.set(index+1));
anim.setRate(1);
anim.play();
});
Button reverseButton = new Button("Play backward");
reverseButton.setOnAction(event -> {
int index = nextTransitionIndex.get()-1;
Animation anim = transitions.get(index);
anim.setOnFinished(evt -> nextTransitionIndex.set(index));
anim.setRate(-1);
anim.play();
});
// This is not really part of the answer to the current question, but the
// next three statements just disable the buttons when appropriate.
// This is a binding which is true if and only if any of the transitions are
// currently running:
BooleanBinding anyPlaying = createAnyPlayingBinding(transitions);
// Disable playButton if we are at the end of the last transition, or if
// any transitions are playing:
playButton.disableProperty().bind(
nextTransitionIndex.greaterThanOrEqualTo(transitions.size())
.or(anyPlaying)
);
// Disable reverseButton if we are at the beginning of the first transition,
// or if any transitions are currently playing:
reverseButton.disableProperty().bind(
nextTransitionIndex.lessThanOrEqualTo(0)
.or(anyPlaying));
HBox controls = new HBox(5);
controls.setAlignment(Pos.CENTER);
controls.getChildren().addAll(playButton, reverseButton);
BorderPane root = new BorderPane();
root.setCenter(pane);
root.setBottom(controls);
primaryStage.setScene(new Scene(root, 800, 400));
primaryStage.show();
}
private BooleanBinding createAnyPlayingBinding(List<Animation> transitions) {
return new BooleanBinding() {
{ // Anonymous constructor
// bind to the status properties of all the transitions
// (i.e. mark this binding as invalid if any of the status properties change)
transitions.stream()
.map(Animation::statusProperty)
.forEach(this::bind);
}
#Override
protected boolean computeValue() {
// return true if any of the transitions statuses are equal to RUNNING:
return transitions.stream()
.anyMatch(anim -> anim.getStatus()==Status.RUNNING);
}
};
}
public static void main(String[] args) {
launch(args);
}
}
In JDK 7, the event handler for the playButton looks like this:
playButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
final int index = nextTransitionIndex.get();
Animation anim = transitions.get(index);
anim.setOnFinished(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent evt) {
nextTransitionIndex.set(index + 1) ;
}
});
anim.setRate(1);
anim.play();
}
});
and similarly for reverseButton. You will need to declare a couple of things as final as well. The createAnyPlayingBinding method is something like
private BooleanBinding createAnyPlayingBinding(final List<Animation> transitions) {
return new BooleanBinding() {
{
for (Animation transition : transitions) {
this.bind(transition.statusProperty();
}
}
#Override
protected boolean computeValue() {
// return true if any of the transitions statuses are equal to RUNNING:
for (Animation anim : transitions) {
if (anim.getStatus() == Status.RUNNING) {
return true ;
}
}
return false ;
}
};
}
I am using JavaFX to build a GUI and I'm having problems on knowing the mouse location when resized. The idea is that if a mouse gets on the very edge of the GUI it changes to a double sided arrow indicating that you can now press the mouse and resize the window.
I need the location of the mouse pointer on this edge, but I don't know how to do that. I need to know in which direction the window is resized.
Updated Added new options and discussed pros and cons.
This is tricky. The issue is that the window keeps track of its top, left, width, and height. When it is resized from the right or bottom, things are easy enough: the width or height change. But when it is resized from the left, both x and width must change. These two changes do not happen atomically, as x and width are stored as two independent properties.
The first approach to this is to keep track of the mouse coordinates, and just see if it's in the left half or the right half. (Obviously you can do the same with the height.) This approach is independent of any implementation details, but the user can cause it to fail by being extremely careful with the mouse. If you move the mouse to the right edge of the window to the exact pixel of the window boundary, then resize, you can see incorrect output.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
class MouseLocation {
double x,y ;
}
MouseLocation mouseLocation = new MouseLocation();
scene.setOnMouseMoved(event -> {
mouseLocation.x = event.getX();
mouseLocation.y = event.getY();
});
primaryStage.widthProperty().addListener((obs, oldWidth, newWidth) -> {
if (mouseLocation.x < primaryStage.getWidth() / 2) {
System.out.println("Resized from left");
} else {
System.out.println("Resized from right");
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The second approach is to keep track of the last known horizontal range of the window (minX and maxX), and update that range when the width changes. Then you can check to see whether the minX or maxX has changed. The problem with this approach is that it's dependent on undocumented implementation details. It appears (on my system, using the current version, etc) that when the window is resized from the left, x is changed first, then the width is changed. If that were to change in a subsequent release, the following would break:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
class MutableDouble {
double value ;
}
MutableDouble windowLeftEdge = new MutableDouble();
primaryStage.widthProperty().addListener((obs, oldWidth, newWidth) -> {
if (primaryStage.getX() == windowLeftEdge.value) {
System.out.println("Resized from right");
} else {
System.out.println("Resized from left");
}
windowLeftEdge.value = primaryStage.getX() ;
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The third approach (that I can think of) is to coalesce changes that happen quickly into a single change. This is a bit tricky to program correctly, so instead of doing it from scratch, I used the third party ReactFX framework which models "event streams" and has a built-in mechanism for combining events that happen in quick succession. This is probably the most robust of the three solutions presented here, but at the cost of either a degree of complexity, or the inclusion of an external framework.
import java.time.Duration;
import org.reactfx.Change;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ObservableValue;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ReactFXVersion extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
ObservableValue<Bounds> windowBounds = Bindings.createObjectBinding(() ->
new BoundingBox(primaryStage.getX(), primaryStage.getY(), primaryStage.getWidth(), primaryStage.getHeight()),
primaryStage.xProperty(), primaryStage.yProperty(), primaryStage.widthProperty(), primaryStage.heightProperty());
EventStream<Change<Bounds>> bounds = EventStreams.changesOf(windowBounds)
.reduceSuccessions((previousChange, nextChange) ->
new Change<>(previousChange.getOldValue(), nextChange.getNewValue()),
Duration.ofMillis(10));
bounds.subscribe(boundsChange -> {
Bounds newBounds = boundsChange.getNewValue();
Bounds oldBounds = boundsChange.getOldValue();
if (newBounds.getWidth() != oldBounds.getWidth()) {
if (newBounds.getMinX() != oldBounds.getMinX()) {
System.out.println("Resized from left");
} else if (newBounds.getMaxX() != oldBounds.getMaxX()) {
System.out.println("Resized from right");
}
}
if (newBounds.getHeight() != oldBounds.getHeight()) {
if (newBounds.getMinY() != oldBounds.getMinY()) {
System.out.println("Resized from top");
} else if (newBounds.getMaxY() != oldBounds.getMaxY()) {
System.out.println("Resized from bottom");
}
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}