Layout of elements inside of HBox for JavaFX - java

I want to loop through each object of a list. For each entry I want to create a GUI object that looks like this:
A checkbox on the left
An image in the center
(later) A label on the left
My problem is, that each label has a different length and it looks rather strange if not all pictures are on the same line (as seen vertically). Is there a possibility by either java or css to align the ImageVew in center of the HBox?
imageView.setLayoutX(filterBox.getWidth()/2); didn't do the trick unfortunatly. And no -fx-align: right; or -fx-float: right; seems to be existing.
I included what I have so far.
VBox filtersBox = new VBox();
HBox filterBox;
for(Filter filter : filters.getFilters()){
if(!filter.isComplex()){
filterBox = new HBox();
filterBox.getStyleClass().add("filter");
ImageView imageView = new ImageView();
[image view stuff]
final CheckBox cbox = new CheckBox(filter.getName().toString());
filterBox.getChildren().addAll(cbox, imageView);
filtersBox.getChildren().addAll(filterBox);
}
}

As far as I'm aware, this is impossible.
I see two ways you can achieve this layout, though:
Have all the checkboxes have the same (constant) preferred width. This way your image views should line up.
Use a GridPane, and add rows instead of HBoxes

Related

setX and setY not working when trying to position images

I am having problems with positioning my images in my JavaFX program using setX and setY on the ImageView's for the images. I am not sure what is the problem? Appreciate any help given!
Here's my code:
Image rocket2 = new Image("img/Rocket.png");
ImageView iv1 = new ImageView(rocket2);
iv1.setX(60);
iv1.setY(44);
Image rocket1 = new Image("img/Rocket.png");
ImageView iv2 = new ImageView(rocket1);
iv2.setX(5);
iv2.setY(16);
Image background = new Image("img/space.png");
ImageView iv3 = new ImageView(background);
StackPane root = new StackPane();
root.getChildren().addAll(iv3, iv2, iv1);
Scene scene = new Scene(root, 300, 300);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.setTitle("Space stuff");
primaryStage.show();
I suspect that something goes wrong because I have set a background image.
img here on what's happening
Don't place your items in a StackPane if you want to explicitly define their layout positions (setX and setY). A StackPane is a managed layout pane. It will automatically set the location of items added to it (default is to center everything one on top of the other inside the StackPane).
Instead use a Pane or a Group, which are not managed layout panes and allow you to layout your content in the Pane however you wish.
To layout your content inside the Pane, you can use setLayoutX and setLayoutY rather than setX and setY, though I guess setX and setY should also work (I've never used them before on ImageView).
Pavlo, already created an answer while I was typing this (so this answer is a duplicate), but I'll leave this as it adds a bit more explanation.
Replacing StackPane with Pane should solve the problem.
If you however want for whatever reason to position a item in a StackPane you can use setTranslateX and setTranslateY. Theese methods set the x and y values AFTER the StackPane has done its layouting, so you will have a different starting position depending on the Alignment your StackPane uses for its children.

JavaFX - How do you add multiple elements to a StackPane?

I'm new to JavaFX. I'm trying to create a simple centred menu that contains text with buttons below.
I've created two elements, Text title and Button testButton. Then I created StackPane stackPane. I'm then trying to add the two elements to the stackPanes children and adding that to a new Scene. However, only the last element shows up.
How can I add multiple elements to the StackPane?
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Test Title");
Text title = new Text("hey!");
StackPane.setAlignment(title, Pos.TOP_CENTER);
Button testButton = new Button("Testing");
StackPane.setAlignment(testButton, Pos.TOP_CENTER);
StackPane stackPane = new StackPane();
stackPane.setPrefSize(300, 300);
stackPane.setPadding(new Insets(25, 0, 0, 0));
stackPane.getChildren().add(title);
stackPane.getChildren().add(testButton);
Scene scene = new Scene(stackPane);
primaryStage.setScene(scene);
primaryStage.show();
}
I want to reference the official documentation here: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.html, especially:
StackPane lays out its children in a back-to-front stack.
The z-order of the children is defined by the order of the children list with the 0th child being the bottom and last child on top. If a border and/or padding have been set, the children will be layed out within those insets.
Now, to answer your question: You do it as you did, but you probably want an offset as both the children are at the same position, hence the one later added is overlaying all the previous ones.
You can check that by changing e.g.
Text title = new Text("Adding a very, very, very, very, very, very long text here... now that vile button should not overlap me anymore!");
or setting the alignment differently.
If you don't want to bother with the optimal layout by manually positioning, it's probably better to use another Pane that does that for you, e.g. one of the direct known subclasses here: https://docs.oracle.com/javafx/2/api/javafx/scene/layout/Pane.html

Getting the absolute coordinates of a node in a BorderPane with some null regions

I have a set of custom made "buttons" for the menu screen of my game. It's basically a StackPane with a Rectangle and a Text node stacked. Basically this is similar to how my buttons are structured.
Pane button1 = new StackPane(new Rectangle(100, 50), new Text("Play!"));
Pane button2 = [....];
Then I insert buttons into a VBox and into my menu along with a header text:
VBox buttons = new VBox(button1, button2, button3...);
Pane menuScreen = new BorderPane(buttons, new Text("The Game"), null, null, null);
However, for my custom detection for mouse position compared to the buttons I need to know the buttons' positions...
int x = button1.getLayoutX(); //returns 0
int x = button1.getTranslateX(); //returns 0
int x = button1.localToScene(0, 0).getX(); //returns 0
int x = button1.localToScene(buttons.get(0).getBoundsInLocal()).getMinX(); //returns 0
int x = button1.localToScene(buttons.get(0).getBoundsInLocal()).getMaxX(); //returns the width of the entire scene
int x = buttons.get(0).getTranslateX(); //returns 0
int y = button1.localToScene(buttons.get(0).getBoundsInLocal()).getMinY();
The last case returns 234.0 if I have the VBox set with .setAlignment(Pos.CENTER) and 64.0 if I don't. But for .getMinX() it stays at 0.0 in either case. I believe it's related to the BorderPane's left/right/bot regions being set to null while the top region has the title text.
I cannot find any way of getting the x coordinate when the buttons are in a layout pane other than the Pane class itself. I tried StackPane as well. My suspicion is that there is no fixed coordinate and that properties are involved, but I only get confused from reading about it when I don't know what I'm looking for.
I have tried solutions from this quesion and this seems to be the same but as I mentioned I'm afraid my minX() doesn't have a set value since the VBox is the only thing filling the center row of my BorderPane.
Edit: StackPane seems to give the right values for .getMinX() when I use .setAlignment(Pos.CENTER), but I am not allowed to do that with the text, only with the VBox, so then the text gets stuck on top of the buttons.
My issue was cause by the VBox and my StackPanes taking up all the possible space, not just the area of the visible Rectangle. Problem was solved by calling setMaxWidth(100) on the StackPane which contained the Rectangle and the Text.
Also, the only problem seems to be that you have a zero x-coordinate. Maybe this is "real". Set a background on button1 to see where it is in the layout. – James_D

JavaFx Images in Gridpane slowing down performance drastically

I want to create a GridPane (which is nested in a ScrollPane) where I add dynamically cells to the GridPane. Each cell contains a VBox with a BackgroundImage, a few Labels and a Checkbox. The Problem is, that the GridPane can contain several hundreds VBoxes, in my case there are about 300 VBoxes and with this many VBoxes the response time of the Gridpane gets really poor. When I click for instance on a CheckBox it takes a few seconds until the CheckBox is selected/unselected, which makes my program pretty much unusable. Without the BackgroundImage the response time of the GridPane is perfect, so I know that the problem here are the Images
This is my Code to create a VBox:
private VBox createAlbumVBox(Album album) {
VBox container = new VBox();
container.setAlignment(Pos.BOTTOM_LEFT);
CheckBox checkBox = new CheckBox();
Label labelAlbum = new Label(album.getName());
Label labelArtist = new Label(album.getArtistName());
labelAlbum.setStyle("-fx-text-fill: #272727");
labelArtist.setStyle("-fx-text-fill: #272727");
Background background;
if(album.getCover() != null)
{
byte[] coverData = album.getCover();
Image image = new Image(new ByteArrayInputStream(coverData));
BackgroundSize bg = new BackgroundSize(100,100,true,true,true,false);
BackgroundImage backgroundImage = new BackgroundImage(image,BackgroundRepeat.NO_REPEAT,BackgroundRepeat.NO_REPEAT,BackgroundPosition.CENTER,bg);
background = new Background(backgroundImage);
}
else
{
Image image = new Image("/ressources/covers/default-cover.png");
BackgroundSize bg = new BackgroundSize(100,100,true,true,true,false);
BackgroundImage backgroundImage = new BackgroundImage(image,BackgroundRepeat.NO_REPEAT,BackgroundRepeat.NO_REPEAT,BackgroundPosition.CENTER,bg);
background = new Background(backgroundImage);
}
checkBox.setOnMouseClicked(e -> {
if (checkBox.isSelected()) {
album.getTitles().forEach(t -> t.setReadyToSync(true));
} else {
album.getTitles().forEach(t -> t.setReadyToSync(false));
}
});
container.setBackground(background);
HBox hBox = new HBox();
hBox.getChildren().addAll(labelAlbum, labelArtist, checkBox);
hBox.setPrefHeight(30);
hBox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.4)");
container.getChildren().addAll(hBox);
return container;
}
I already tried to use an ImageView instead of a BackgroundImage. Unfortunately the performance with an ImageView is as poor as with a BackgroundImage.
This is not really an answer but more a set of suggestions you can try. It's hard to comment on performance issues without a complete mcve, which would allow the issues to be easily reproduced locally in a minimal application.
Some things you could try are:
Use background loading for your images.
Cache loaded images in a LRU cache.
Use a virtualized control, such as a ControlsFX GridView.
See also some of the performance optimization suggestions in a related answer (some of which may not be applicable to your situation):
What is the best way to display millions of images in Java?
Also, your issue could be in code that you don't show. Your routine is being passed an Album instance which includes album data, including image data in binary form. If you load up your album data and images from a database dynamically, then that process could slow or freeze your application, depending upon how you do it.

When adding a second item to my stackpane, the first item loses its Event/MouseOn. Why? How can I fix? JavaFX

I have a stackpane. When I add a second item to my stack pane, both show up, but I can't click on my first item anymore. It becomes 'unclickable'.
what ever I defined in my .setonmouse does not work. It works for my second item. If I switch the order they are in the stack pane, the other one works, but not both.
is there a fix for this? This is what my program looks like:
I want my 'grid' centered ALWAYS. There are buttons to the left centered in a column, there will be buttons on the right later on, and there will be buttons/Text on top of the grid and buttom in the margins later on too.
I want everything to be clickable.
http://img688.imageshack.us/img688/6025/examplerg.png
StackPane orders items in Z-order: latter above the former. So, your second item gots all mouse clicks and first one (being covered by second) doesn't get anything.
For layout you've described you can use BorderPane:
public void start(Stage stage) throws Exception {
BorderPane root = new BorderPane();
root.setCenter(new Rectangle(100,100, Color.RED));
root.setLeft(new Rectangle(10,10, Color.BLUE));
root.setRight(new Rectangle(10,10, Color.CYAN));
stage.setScene(new Scene(root,300,300));
stage.show();
}
You can make any Pane "mouse transparent", so that it doesn't consume any click events, and lets them pass through to the stack under it.
Here's some example code... this example sets up 4 panes in a stack, with just the mainPane accepting clicks to begin with.
StackPane rootPane = new StackPane();
VBox mainPane = new VBox(80);
BorderPane helpOverlayPane = new BorderPane();
helpOverlayPane.setMouseTransparent(true);
Canvas fullScreenOverlayCanvas = new Canvas();
fullScreenOverlayCanvas.setMouseTransparent(true);
VBox debugPane = new VBox();
debugPane.setAlignment(Pos.BASELINE_RIGHT);
AnchorPane debugOverlay = new AnchorPane();
debugOverlay.setMouseTransparent(true);
debugOverlay.getChildren().add(debugPane);
AnchorPane.setBottomAnchor(debugPane, 80.0);
AnchorPane.setRightAnchor(debugPane, 20.0);
rootPane.getChildren().addAll(mainPane, fullScreenOverlayCanvas, debugOverlay, helpOverlayPane);
Now, when you want to use your canvas to draw on top, make sure you change mouse transparent to false for just that stack, and keep all panes on top of it mouse transparent.
fullScreenOverlayCanvas.setMouseTransparent(false);
debugOverlay.setMouseTransparent(true);
fullScreenOverlayCanvas.setVisible(true);
doSomethingWithCanvasThatNeedsMouseClicks();
P.S. I did some editing of the code I had, so it may not run as-is. Also, see discussion of making only parts of panes transparent here:
JavaFX Pass MouseEvents through Transparent Node to Children

Categories