I have a class which extends StackPane. Another one which makes a 20x20 2d Array of this class. I then translated their position somewhere on the scene. Right now, I can't obtain the position of a cell relative on the scene.
I tried Bounds, Point2D.zero and getMin..
cell.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
System.out.println("mouse click detected! " + mouseEvent.getSource());
// boundsInScene = cell.localToScene(cell.getLayoutBounds());
// System.out.println("Cell width: " + boundsInScene.getMinX());
// System.out.println("Cell height: " + boundsInScene.getMinY());
// cell.localToScene(Point2D.ZERO);
int x = (int) cell.getTranslateX();
int y = (int) cell.getTranslateY();
System.out.println("X: " + x + "y :" + y);
}
});
Part of my code:
private Parent createContent() {
root = new Pane();
root.setPrefSize(640, 480);
for (int col = 0; col < y_Tiles; col++) {
for (int row = 0; row < x_Tiles; row++) {
cell = new Cell(row, col);
grid_Array[row][col] = cell;
cell.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {});
root.getChildren().add(cell);
}
}
return root;
}
Bounds is resturning me 480 and 400. Another thing is that all cells return the same output for any of the methods I tried. Any idea how to cell the position of a cell on the scene?
PS:Sorry for bad english. Not native language
You shouldn't be using translateX/Y to set the location of your items. translateX/Y should just be used for temporary movements of an item, such as a bounce effect or a transition. layoutX/Y should be used to set the location of items. Normally layoutX/Y will be set automatically by a layout pane. If you aren't using a layout pane and are manually performing the layout in an unmanaged parent (such as a Pane or a Group), then you can manually set the layoutX/Y values as needed (relocate will do this).
Once you switch to setting the layout values rather than the translate values, then you determine the location of any node in a scene using the localToScene function.
Bounds boundsInScene = node.localToScene(node.getLayoutBounds());
Related
I have a FlowPane with equally-sized rectangular children and I have this problem with the space at the right end of the flowpane, when the space is not enough to fit another column of children, I want it to be equally divided between the other columns.
An example of what I want to achieve is how the file explorer in windows behaves, see the gif bellow for reference
The default FlowPane behaviour doesn't look like this, it leaves the remaining width that can't fit a new child at the end of the region, as shown in the gif bellow
And I failed to find any API or documentation to help me achieve my goal, I thought of adding a listener on the width property and adjusting the hGap property accordingly, something like
[ flowPaneWidth - (sum of the widths of the children in one column) ] / (column count - 1)
But again, I have no idea how to figure out the column count, so any help would be appreciated.
Here is a MRE if anyone wants to try their ideas :
public class FPAutoSpace extends Application {
#Override
public void start(Stage ps) throws Exception {
FlowPane root = new FlowPane(10, 10);
root.setPadding(new Insets(10));
for(int i = 0; i < 20; i++) {
root.getChildren().add(new Rectangle(100, 100, Color.GRAY));
}
ps.setScene(new Scene(root, 600, 600));
ps.show();
}
}
After a bit of thinking, I tried to implement the idea mentioned in the question :
adding a listener on the width property and adjusting the hGap property accordingly
but I added the listener on the needsLayout property instead, as follows :
public class FPAutoSpace extends Application {
private double nodeWidth = 100;
#Override
public void start(Stage ps) throws Exception {
FlowPane root = new FlowPane();
root.setVgap(10);
for (int i = 0; i < 20; i++) {
root.getChildren().add(new Rectangle(nodeWidth, nodeWidth, Color.GRAY));
}
root.needsLayoutProperty().addListener((obs, ov, nv) -> {
int colCount = (int) (root.getWidth() / nodeWidth);
//added 4 pixels because it gets glitchy otherwise
double occupiedWidth = nodeWidth * colCount + 4;
double hGap = (root.getWidth() - occupiedWidth) / (colCount - 1);
root.setHgap(hGap);
});
StackPane preRoot = new StackPane(root);
preRoot.setPadding(new Insets(10));
preRoot.setAlignment(Pos.TOP_LEFT);
ps.setScene(new Scene(preRoot, 600, 600));
ps.show();
}
}
Not sure how this will hold up in a multi-hundred node FlowPane but it worked for the MRE
Let me know if you think there are better ways to do it.
I am trying to make the bouncing DVD logo as a means of learning to use timeline and keyframe in javaFX. The problem I am running in to is if I set the X/Y of the image to anything other than 0,0 the image will go further than the bounds of the screen. I am just confused on why this is happening and what I need to do to fix it. Thank you!
I have tried setting the image to different areas on the pane. I have tried subtracting more than just the dvd width and height to compensate. I have tried many things.
public class Main extends Application {
Stage window;
private final int WIDTH = 700;
private final int HEIGHT = 700;
private Timeline timeline;
private double xSpeed = 3;
private double ySpeed = 3;
private Parent createContent() {
Pane root = new Pane();
root.setPrefSize(WIDTH,HEIGHT);
ImageView dvd = new ImageView(new Image("/dvd.png"));
dvd.setFitHeight(100);
dvd.setFitWidth(100);
dvd.setPreserveRatio(true);
dvd.setX(100);
dvd.setY(100);
dvd.setPreserveRatio(true);
timeline = new Timeline(new KeyFrame(Duration.millis(16), e-> {
dvd.setTranslateX(dvd.getTranslateX() + xSpeed);
dvd.setTranslateY(dvd.getTranslateY() + ySpeed);
if (xSpeed + dvd.getTranslateX() >= WIDTH - dvd.getFitWidth()){
xSpeed = -xSpeed;
} else if(xSpeed + dvd.getTranslateX() <= 0)
xSpeed = -xSpeed;
if (ySpeed + dvd.getTranslateY() >= HEIGHT - dvd.getFitHeight()){
ySpeed = -ySpeed;
} else if(ySpeed + dvd.getTranslateY() <= 0)
ySpeed = -ySpeed;
}));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
root.getChildren().add(dvd);
return root;
}
#Override
public void start(Stage primaryStage) throws Exception{
window = primaryStage;
Scene mainScene = new Scene(createContent(),WIDTH,HEIGHT);
window.setResizable(false);
window.setTitle("Bouncing DVD");
window.setScene(mainScene);
window.show();
}
public static void main(String[] args) {
launch(args);
}
}
I expect to be able to place the DVD image anywhere on the screen and for it to bounce off of the walls of the scene.
The x and y properties of ImageView are ways of moving the ImageView from it's usual position without affecting the translate properties. Any changes of the rendering position by transforms such as the translate properties happen in addition to this change.
The x and y ranges where the image is rendered are [x+translateX, x+translateX+fitWidth) and[y+translateY, y+translateY+fitHeight) respectively.
The simplest way of fixing this issue is using only a single property per dimension, e.g. translateX and translateY:
dvd.setFitHeight(100);
dvd.setFitWidth(100);
dvd.setPreserveRatio(true);
dvd.setTranslateX(100);
dvd.setTranslateY(100);
I am coding a slider puzzle, using a 2-D array of buttons where 1 button is blank at all times, and the remaining buttons can only move if they are next to the blank button. Would anyone be able to offer a way to check the surrounding buttons and determine if it borders on the blank one? (keeping in mind boundaries)
Create fields blankX and blankY that contain the current position of the blank.
For each button save the current position in the properties. This allows you to retrieve the coordinates of the button, check, if they are adjacent to the blank and swap the positions, if that's the case.
Example:
private int blankX = 0;
private int blankY = 0;
private static final int SIZE = 50;
private static final String X_KEY = "TileLocationX";
private static final String Y_KEY = "TileLocationY";
private void move(Node n, int x, int y) {
// adjust position
n.setLayoutX(blankX * SIZE);
n.setLayoutY(blankY * SIZE);
// save coordinates to property
n.getProperties().put(X_KEY, blankX);
n.getProperties().put(Y_KEY, blankY);
// save node pos as blank pos
blankX = x;
blankY = y;
}
#Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
EventHandler<ActionEvent> handler = evt -> {
Node n = (Node) evt.getSource();
int x = (Integer) n.getProperties().get(X_KEY);
int y = (Integer) n.getProperties().get(Y_KEY);
if (Math.abs(x - blankX) + Math.abs(y - blankY) == 1) {
// move button, if it's adjacent to the blank
move(n, x, y);
}
};
int count = 1;
// create grid
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i != blankX || j != blankY) {
Button button = new Button(Integer.toString(count++));
button.setPrefSize(SIZE, SIZE);
button.setLayoutX(SIZE * i);
button.setLayoutY(SIZE * j);
button.getProperties().put(X_KEY, i);
button.getProperties().put(Y_KEY, j);
button.setOnAction(handler);
pane.getChildren().add(button);
}
}
}
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
2D arrays make it easy. Check for null above, below, right, and left, making sure that you aren't going out of bounds (aka checking boxes off the actual game grid).
I'm not sure if JavaFX is different from Java, so I can only give pseudo code:
//initialize int[5][5] (position) with tile classes (Tile), setting one to null
//checking tile at position[a][b]
//check position[a-1][b], [a+1][b], [a][b-1], [a][b+1] for null...
//...also making sure the value is between 0 and 5
//if any of those is true, square is moveable!
There might be an even more efficient way to do this, however. If you add another variable (boolean isMoveable) to each tile, then you can start each turn by finding the empty square and simply checking off every tile it borders as moveable. This would even allow you to highlight them somehow at the beginning of the turn, so the player knows what he can move.
And if you don't want to search through the entire board for the empty square, you can simply do it once at the beginning and save it's position to an array. Next turn, look to each square bordering that position to find the empty one.
If you have a 2D array, then you have the x and y location of each button. Keep the location of the blank button in variables, say blankX and blankY.
Then the condition for a button to be adjacent to the blank button is
Either x==blankX and y and blankY differ by 1, or
y==blankY and x and blankX differ by 1
So if you do
int deltaX = Math.abs(x - blankX) ;
int deltaY = Math.abs(y - blankY) ;
the condition is
deltaX==0 && deltaY==1, or
deltaX==1 && deltaY==0
but since deltaX >= 0 and deltaY >= 0, this is just equivalent to
deltaX + deltaY == 1
If you make blankX and blankY JavaFX properties:
private final IntegerProperty blankX = new SimpleIntegerProperty();
private final IntegerProperty blankY = new SimpleIntegerProperty();
then you can easily disable the button when it's not adjacent to the blank buttons:
// creates a button with coordinates x,y and initializes it
private Button createButton(int x, int y) {
Button button = new Button(Integer.toString(x + y * numColumns + 1));
// disable if not adjacent to blank button:
button.disableProperty().bind(Bindings.createBooleanBinding(
() -> Math.abs(x - blankX.get()) + Math.abs(y - blankY.get()) != 1,
blankX, blankY));
// when pressed, swap with blank button and update blankX, blankY:
button.setOnAction(e -> {
buttonArray[blankX.get()][blankY.get()].setText(button.getText());
button.setText("");
blankX.set(x);
blankY.set(y);
});
return button ;
}
I have a sample 3D application (built by taking reference from the Javafx sample 3DViewer) which has a table created by laying out Boxes and Panes:
The table is centered wrt (0,0,0) coordinates and camera is at -z position initially.
It has the zoom-in/out based on the camera z position from the object.
On zooming in/out the object's boundsInParent increases/decreases i.e. area of the face increases/decreases. So the idea is to put more text when we have more area (always confining within the face) and lesser text or no text when the face area is too less. I am able to to do that using this node hierarchy:
and resizing the Pane (and managing the vBox and number of texts in it) as per Box on each zoom-in/out.
Now the issue is that table boundsInParent is giving incorrect results (table image showing the boundingBox off at the top) whenever a text is added to the vBox for the first time only. On further zooming-in/out gives correct boundingBox and does not go off.
Below is the UIpane3D class:
public class UIPane3D extends Pane
{
VBox textPane;
ArrayList<String> infoTextKeys = new ArrayList<>();
ArrayList<Text> infoTextValues = new ArrayList<>();
Rectangle bgCanvasRect = null;
final double fontSize = 16.0;
public UIPane3D() {
setMouseTransparent(true);
textPane = new VBox(2.0)
}
public void updateContent() {
textPane.getChildren().clear();
getChildren().clear();
for (Text textNode : infoTextValues) {
textPane.getChildren().add(textNode);
textPane.autosize();
if (textPane.getHeight() > getHeight()) {
textPane.getChildren().remove(textNode);
textPane.autosize();
break;
}
}
textPane.setTranslateY(getHeight() / 2 - textPane.getHeight() / 2.0);
bgCanvasRect = new Rectangle(getWidth(), getHeight());
bgCanvasRect.setFill(Color.web(Color.BURLYWOOD.toString(), 0.10));
bgCanvasRect.setVisible(true);
getChildren().addAll(bgCanvasRect, textPane);
}
public void resetInfoTextMap()
{
if (infoTextKeys != null || infoTextValues != null)
{
try
{
infoTextKeys.clear();
infoTextValues.clear();
} catch (Exception e){e.printStackTrace();}
}
}
public void updateInfoTextMap(String pKey, String pValue)
{
int index = -1;
boolean objectFound = false;
for (String string : infoTextKeys)
{
index++;
if(string.equals(pKey))
{
objectFound = true;
break;
}
}
if(objectFound)
{
infoTextValues.get(index).setText(pValue.toUpperCase());
}
else
{
if (pValue != null)
{
Text textNode = new Text(pValue.toUpperCase());
textNode.setFont(Font.font("Consolas", FontWeight.BLACK, FontPosture.REGULAR, fontSize));
textNode.wrappingWidthProperty().bind(widthProperty());
textNode.setTextAlignment(TextAlignment.CENTER);
infoTextKeys.add(pKey);
infoTextValues.add(textNode);
}
}
}
}
The code which get called at the last after all the manipulations:
public void refreshBoundingBox()
{
if(boundingBox != null)
{
root3D.getChildren().remove(boundingBox);
}
PhongMaterial blueMaterial = new PhongMaterial();
blueMaterial.setDiffuseColor(Color.web(Color.CRIMSON.toString(), 0.25));
Bounds tableBounds = table.getBoundsInParent();
boundingBox = new Box(tableBounds.getWidth(), tableBounds.getHeight(), tableBounds.getDepth());
boundingBox.setMaterial(blueMaterial);
boundingBox.setTranslateX(tableBounds.getMinX() + tableBounds.getWidth()/2.0);
boundingBox.setTranslateY(tableBounds.getMinY() + tableBounds.getHeight()/2.0);
boundingBox.setTranslateZ(tableBounds.getMinZ() + tableBounds.getDepth()/2.0);
boundingBox.setMouseTransparent(true);
root3D.getChildren().add(boundingBox);
}
Two things:
The table3D's boundsInParent is not updated properly when texts are added for the first time.
What would be the right way of putting texts on 3D nodes? I am having to manipulate a whole lot to bring the texts as required.
Sharing code here.
For the first question, about the "jump" that can be noticed just when after scrolling a new text item is laid out:
After digging into the code, I noticed that the UIPane3D has a VBox textPane that contains the different Text nodes. Every time updateContent is called, it tries to add a text node, but it checks that the vbox's height is always lower than the pane's height, or else the node will be removed:
for (Text textNode : infoTextValues) {
textPane.getChildren().add(textNode);
textPane.autosize();
if (textPane.getHeight() > getHeight()) {
textPane.getChildren().remove(textNode);
textPane.autosize();
break;
}
}
While this is basically correct, when you add a node to the scene, you can't get textPane.getHeight() immediately, as it hasn't been laid out yet, and you have to wait until the next pulse. This is why the next time you scroll, the height is correct and the bounding box is well placed.
One way to force the layout and get the correct height of the textNode is by forcing css and a layout pass:
for (Text textNode : infoTextValues) {
textPane.getChildren().add(textNode);
// force css and layout
textPane.applyCss();
textPane.layout();
textPane.autosize();
if (textPane.getHeight() > getHeight()) {
textPane.getChildren().remove(textNode);
textPane.autosize();
break;
}
}
Note that:
This method [applyCss] does not normally need to be invoked directly but may be used in conjunction with Parent.layout() to size a Node before the next pulse, or if the Scene is not in a Stage.
For the second question, about a different solution to add Text to 3D Shape.
Indeed, placing a (2D) text on top of a 3D shape is quite difficult, and requires complex maths (that are done quite nicely in the project, by the way).
There is an alternative avoiding the use of 2D nodes directly.
Precisely in a previous question, I "wrote" into an image, that later on I used as the material diffuse map of a 3D shape.
The built-in 3D Box places the same image into every face, so that wouldn't work. We can implement a 3D prism, or we can make use of the CuboidMesh node from the FXyz3D library.
Replacing the Box in UIPaneBoxGroup:
final CuboidMesh contentShape;
UIPane3D displaypane = null;
PhongMaterial shader = new PhongMaterial();
final Color pColor;
public UIPaneBoxGroup(final double pWidth, final double pHeight, final double pDepth, final Color pColor) {
contentShape = new CuboidMesh(pWidth, pHeight, pDepth);
this.pColor = pColor;
contentShape.setMaterial(shader);
getChildren().add(contentShape);
addInfoUIPane();
}
and adding the generateNet method:
private Image generateNet(String string) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
Label label5 = new Label(string);
label5.setFont(Font.font("Consolas", FontWeight.BLACK, FontPosture.REGULAR, 40));
GridPane.setHalignment(label5, HPos.CENTER);
grid.add(label5, 3, 1);
double w = contentShape.getWidth() * 10; // more resolution
double h = contentShape.getHeight() * 10;
double d = contentShape.getDepth() * 10;
final double W = 2 * d + 2 * w;
final double H = 2 * d + h;
ColumnConstraints col1 = new ColumnConstraints();
col1.setPercentWidth(d * 100 / W);
ColumnConstraints col2 = new ColumnConstraints();
col2.setPercentWidth(w * 100 / W);
ColumnConstraints col3 = new ColumnConstraints();
col3.setPercentWidth(d * 100 / W);
ColumnConstraints col4 = new ColumnConstraints();
col4.setPercentWidth(w * 100 / W);
grid.getColumnConstraints().addAll(col1, col2, col3, col4);
RowConstraints row1 = new RowConstraints();
row1.setPercentHeight(d * 100 / H);
RowConstraints row2 = new RowConstraints();
row2.setPercentHeight(h * 100 / H);
RowConstraints row3 = new RowConstraints();
row3.setPercentHeight(d * 100 / H);
grid.getRowConstraints().addAll(row1, row2, row3);
grid.setPrefSize(W, H);
grid.setBackground(new Background(new BackgroundFill(pColor, CornerRadii.EMPTY, Insets.EMPTY)));
new Scene(grid);
return grid.snapshot(null, null);
}
Now all the 2D related code can be removed (including displaypane), and after a scrolling event get the image:
public void refreshBomUIPane() {
Image net = generateNet(displaypane.getText());
shader.setDiffuseMap(net);
}
where in UIPane3D:
public String getText() {
return infoTextKeys.stream().collect(Collectors.joining("\n"));
}
I've also removed the bounding box to get this picture:
I haven't played around with the number of text nodes that can be added to the VBox, the font size nor with an strategy to avoid generating images on every scroll: only when the text changes this should be done. So with the current approach is quite slow, but it can be improved notably as there are only three possible images for each box.
I have three problems:
I want to create resizable shapes with box bounding...
I also want to know how to get child seleted in a Pane.
I'm creating multiple shapes on a pane. I want to change some property of that shape say Fill.. How do i do it??
Thanx
Next example will answer your questions:
for (1) it uses binding, connecting pane size with rectangle size
for (2) it adds setOnMouseClick for each rectangle which stores clicked one in the lastOne field.
for (3) see code of setOnMouseClick() handler
public class RectangleGrid extends Application {
private Rectangle lastOne;
public void start(Stage stage) throws Exception {
Pane root = new Pane();
int grid_x = 7; //number of rows
int grid_y = 7; //number of columns
// this binding will find out which parameter is smaller: height or width
NumberBinding rectsAreaSize = Bindings.min(root.heightProperty(), root.widthProperty());
for (int x = 0; x < grid_x; x++) {
for (int y = 0; y < grid_y; y++) {
Rectangle rectangle = new Rectangle();
rectangle.setStroke(Color.WHITE);
rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
if (lastOne != null) {
lastOne.setFill(Color.BLACK);
}
// remembering clicks
lastOne = (Rectangle) t.getSource();
// updating fill
lastOne.setFill(Color.RED);
}
});
// here we position rects (this depends on pane size as well)
rectangle.xProperty().bind(rectsAreaSize.multiply(x).divide(grid_x));
rectangle.yProperty().bind(rectsAreaSize.multiply(y).divide(grid_y));
// here we bind rectangle size to pane size
rectangle.heightProperty().bind(rectsAreaSize.divide(grid_x));
rectangle.widthProperty().bind(rectangle.heightProperty());
root.getChildren().add(rectangle);
}
}
stage.setScene(new Scene(root, 500, 500));
stage.show();
}
public static void main(String[] args) { launch(); }
}