View of the application javafx - javafx

i was searching in google for hours and i still cant find the right answer, so i have a last chance to come here and ask.
i'm making school year JAVA FX project. I'm using NetBeans.
I have a point that i can see on the application i have. The problem is: I would like to have a big map (background) and I need to be able to move with my view. For example move by 50 to the right (x).
I have Application where I use Stage, Scene, StackPane.
I heard something about Dimensions in Java, but i can't use it in javafx application. Is there something similar, what can I use in my Application?
Thank you very much.

What I think you are asking for is a Scene with a map (represented as an Image) in the background and controls layered on top of the map to allow interaction with the map at certain positions. Your question is a little unclear, so I'm not exactly sure if that is what you are asking.
If so, here is some sample code to implement that.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
/** Constructs a scene with a pannable Map background. */
public class PannableView extends Application {
private Image backgroundImage;
#Override public void init() {
backgroundImage = new Image("https://www.narniaweb.com/wp-content/uploads/2009/08/NarniaMap.jpg");
}
#Override public void start(Stage stage) {
stage.setTitle("Drag the mouse to pan the map");
// construct the scene contents over a stacked background.
StackPane layout = new StackPane();
layout.getChildren().setAll(
new ImageView(backgroundImage),
createKillButton()
);
// wrap the scene contents in a pannable scroll pane.
ScrollPane scroll = createScrollPane(layout);
// show the scene.
Scene scene = new Scene(scroll);
stage.setScene(scene);
stage.show();
// bind the preferred size of the scroll area to the size of the scene.
scroll.prefWidthProperty().bind(scene.widthProperty());
scroll.prefHeightProperty().bind(scene.widthProperty());
// center the scroll contents.
scroll.setHvalue(scroll.getHmin() + (scroll.getHmax() - scroll.getHmin()) / 2);
scroll.setVvalue(scroll.getVmin() + (scroll.getVmax() - scroll.getVmin()) / 2);
}
/** #return a control to place on the scene. */
private Button createKillButton() {
final Button killButton = new Button("Kill the evil witch");
killButton.setStyle("-fx-base: firebrick;");
killButton.setTranslateX(65);
killButton.setTranslateY(-130);
killButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent t) {
killButton.setStyle("-fx-base: forestgreen;");
killButton.setText("Ding-Dong! The Witch is Dead");
}
});
return killButton;
}
/** #return a ScrollPane which scrolls the layout. */
private ScrollPane createScrollPane(Pane layout) {
ScrollPane scroll = new ScrollPane();
scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scroll.setPannable(true);
scroll.setPrefSize(800, 600);
scroll.setContent(layout);
return scroll;
}
public static void main(String[] args) { launch(args); }
}
For the example use the mouse (or probably touch commands or trackpad scroll gestures - though I haven't a touch screen or trackpad to test it) to drag the map around. Click on the button to "Kill the evil witch".
The solution works by:
Creating an ImageView to hold the background map.
Constructing the scene contents in a StackPane over the stacked background ImageView.
Wrapping the scene in a ScrollPane bound to the scene's size.
Setting properties on the ScrollPane to make it pannable.

Related

JavaFX ScrollPane - Detect when scrollbar is visible?

I have a ScrollPane as below:
ScrollPane scroller = new ScrollPane();
scroller.getStyleClass().add("scroller");
scroller.setPrefWidth(width);
scroller.setFocusTraversable(Boolean.FALSE);
scroller.setPannable(Boolean.TRUE);
scroller.setFitToWidth(Boolean.TRUE);
scroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
this.setCenter(scroller);
scroller.contentProperty().addListener((observableValue, last, now) ->
{
ScrollBar scrollBar = (ScrollBar) scroller.lookup(".scroll-bar:vertical");
if (scrollBar != null)
{
if (scrollBar.isVisible())
{
log.info("Scrollbar visible, setting lower card width..");
}
else
{
log.info("Scrollbar not visible, setting default card width..");
}
}
});
As you can see I've attached a listener to the content property to know when the content is set. I am trying to see if the scrollbar is visible when the content is updated. Even though I can see the scroll bar on the UI, it always goes to else part - "Scrollbar not visible".
Not sure if there is any other way to do this? Checked a lot on StackOverflow and Oracle docs - nothing solid found to suggest otherwise.
-- Adding context to the problem to better understand:
Just trying to explain what the problem is not sure if I should put it as a reply comment or edit the question, please advise and will change it:
So I have this view that brings up records from Firebase that need to be loaded on the TilePane that is hosted in ScrollPane which goes into the Center of the BorderPane.
The time by which I get the response from the Firebase is unpredictable as its async. So the UI gets loaded up with the empty TilePane and then the async call goes to fetch data. When the data is available, I need to prepare Cards (which is HBox) but the number of columns is fixed. So have to adjust the width of the cards to keep the gap (16px) and padding (16px) consistent on the TilePane at the same time maintain 5 columns. The width of each card needs to be recalculated based on the fact that whether or not there is a scrollbar on the display. Because if the scrollbar is displayed it takes some space and the TilePane will down it to 4 columns leaving a lot of empty space. Happy to explain further if this is not clear.
I strongly suggest to follow the suggestions given in the comments. It is all about choosing the correct layout.
The purpose of me answering this question is, in future, if someone comes across this question for dealing with scroll bar visibility, they will atleast know a way to get that (in JavaFX 8).
One way to check for the scrollbar visiblity is to register the appropriate scrollbar on layoutChildren and add a listener to its visilble property. Something like...
ScrollPane scrollPane = new ScrollPane() {
ScrollBar vertical;
#Override
protected void layoutChildren() {
super.layoutChildren();
if (vertical == null) {
vertical = (ScrollBar) lookup(".scroll-bar:vertical");
vertical.visibleProperty().addListener((obs, old, val) -> updateContent(val));
updateContent(vertical.isVisible());
}
}
};
The updateContent(visible) method is stuff you want to do when the visibility gets updated.
A complete working demo is as below.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ScrollPaneScrollBarVisibility_Demo extends Application {
#Override
public void start(Stage stage) throws Exception {
BorderPane borderPane = new BorderPane();
Scene sc = new Scene(borderPane, 300, 300);
stage.setScene(sc);
stage.setTitle("ScrollBar visibility");
stage.show();
ScrollPane scrollPane = new ScrollPane() {
ScrollBar vertical;
#Override
protected void layoutChildren() {
super.layoutChildren();
if (vertical == null) {
vertical = (ScrollBar) lookup(".scroll-bar:vertical");
vertical.visibleProperty().addListener((obs, old, val) -> updateContent(val));
updateContent(vertical.isVisible());
}
}
};
scrollPane.setContent(getContent());
borderPane.setCenter(scrollPane);
}
private void updateContent(boolean scrollBarVisible) {
System.out.println("Vertical scroll bar visible :: " + scrollBarVisible);
}
private VBox getContent() {
VBox labels = new VBox();
labels.setSpacing(5);
for (int i = 0; i < 10; i++) {
labels.getChildren().add(new Label("X " + i));
}
Button add = new Button("Add");
add.setOnAction(e -> labels.getChildren().add(new Label("Text")));
Button remove = new Button("Remove");
remove.setOnAction(e -> {
if (!labels.getChildren().isEmpty()) {
labels.getChildren().remove(labels.getChildren().size() - 1);
}
});
HBox buttons = new HBox(add, remove);
buttons.setSpacing(15);
VBox content = new VBox(buttons, labels);
content.setPadding(new Insets(15));
content.setSpacing(15);
return content;
}
public static void main(String[] args) {
Application.launch(args);
}
}
As #James_D said, used GridPane and it worked without any listeners:
GridPane cards = new GridPane();
cards.setVgap(16);
cards.setHgap(16);
cards.setAlignment(Pos.CENTER);
cards.setPadding(new Insets(16));
ColumnConstraints constraints = new ColumnConstraints();
constraints.setPercentWidth(20);
constraints.setHgrow(Priority.ALWAYS);
constraints.setFillWidth(Boolean.TRUE);
cards.getColumnConstraints().addAll(constraints, constraints, constraints, constraints, constraints);
I have 5 columns, so 5 times constraints. Worked just fine.

Create a draggable selection box for a sketching program in JavaFX

I'm trying to create a draggable selection box for a sketching program in JavaFX, one like this:
I'm only not sure how to do it. I initially wanted to do it like this: capture the mouse coordinates when the mouse is pressed and do it again at the end of a drag, then calculate the height and width and make a transparent button with a black border with these properties.
But, then I realized that when I do it like this, it is not possible to see the button while you are scaling the plane, unless you draw and delete a lot of buttons.
So, I wondered if there is a better way to do something like this or is my reasoning above right? Thanks
I would use a Rectangle instead of a Button. Just do what you describe, but update the size (and position) of the rectangle on mouse drag, instead of only adding it when the mouse is released.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class SelectionRectangle extends Application {
private double mouseDownX ;
private double mouseDownY ;
#Override
public void start(Stage primaryStage) {
Rectangle selectionRectangle = new Rectangle();
selectionRectangle.setStroke(Color.BLACK);
selectionRectangle.setFill(Color.TRANSPARENT);
selectionRectangle.getStrokeDashArray().addAll(5.0, 5.0);
Pane pane = new Pane();
pane.setMinSize(600, 600);
pane.getChildren().add(selectionRectangle);
pane.setOnMousePressed(e -> {
mouseDownX = e.getX();
mouseDownY = e.getY();
selectionRectangle.setX(mouseDownX);
selectionRectangle.setY(mouseDownY);
selectionRectangle.setWidth(0);
selectionRectangle.setHeight(0);
});
pane.setOnMouseDragged(e -> {
selectionRectangle.setX(Math.min(e.getX(), mouseDownX));
selectionRectangle.setWidth(Math.abs(e.getX() - mouseDownX));
selectionRectangle.setY(Math.min(e.getY(), mouseDownY));
selectionRectangle.setHeight(Math.abs(e.getY() - mouseDownY));
});
primaryStage.setScene(new Scene(pane));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
You can use a mouse released handler to figure out what's selected, by looking at the x, y, width, and height properties of the rectangle, as needed.

How to position a button in JavaFX

I am using NetBeans IDE 8.2 for JavaFX. I already know that in order to change the position of a button I need to use setLayoutX/Y. I have tried this, and there is no effect on the buttons. Here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javafxapplication2;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* #author coolDawg1234
*/
public class JavaFXApplication2 extends Application {
#Override
public void start(Stage primaryStage) {
String x = "1";
String y = "0";
Button btn1 = new Button(x);
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.print(x);
}
});
Button btn2 = new Button(y);
btn2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.print(y);
}
});
StackPane root = new StackPane();
root.getChildren().add(btn1);
btn1.setLayoutX(250);
btn1.setLayoutY(220);
root.getChildren().add(btn2);
btn1.setLayoutX(200);
btn1.setLayoutY(200);
Scene scene = new Scene(root, 1000, 1000);
primaryStage.setTitle("WHAT\'s GOOD MY MANS");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Netbeans gives me 0 errors for this, and everything other than the position of the buttons looks fine to me.
Please help me find my problem.
The container for your buttons is a StackPane. StackPane is an implementation of Pane such that it will, by default, layout its children at the center of itself. Therefore, whenever the scene needs to perform a layout, StackPane will set the layoutX and layoutY values (therefore overwriting whatever you had set) in its layoutChildren() method based on its own layout strategy. This behavior happens for most, if not all, subclasses of Pane.
If you need to manually position your child nodes, you need to use the generic Pane container. You can either choose to subclass it and provide your own layout strategy/logic, or simply set layoutX and layoutY values on the child nodes directly.
If you need the layout strategy provided by StackPane, but you would want it to be positioned slightly different from the default position, then you may be looking for translateXProperty() and translateYProperty().
30 root.getChildren().add(btn1);
31 btn1.setLayoutX(250);
32 btn1.setLayoutY(220);
33 root.getChildren().add(btn2);
34 btn1.setLayoutX(200);
35 btn1.setLayoutY(200);
Just take the right variable (consistent) btn1 gets two coordinates for the same direktion (250 for X in row 31, and 200 for X in row 34), so that button which has no directly set coordinates, has in this layout the coordinates (0,0).

how to fix javafx - tableview size to current window size

I'm totally new to standalone applications. Please any one help me on this.
I have TableView with 6 columns which is half showing in the window as shown below.
I want to fix its current window size, even when the window is expanded, the tableview should auto resize. Is there any way to do this?
This Is The Code Snippet
GridPane tableGrid= new GridPane();
tableGrid.setVgap(10);
tableGrid.setHgap(10);
Label schoolnameL= new Label(SCHOOL+school_id);
schoolnameL.setId("schoolLabel");
Button exportDataSheetBtn= new Button("Export In File");
tableView.setMaxWidth(Region.USE_PREF_SIZE);
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableGrid.getChildren().addAll(schoolnameL,exportDataSheetBtn,tableView);
This can be done by binding the preferred height and width to the height and width of the primary stage. Here's an MCVE:
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class MCVE extends Application {
#Override
public void start(Stage stage) {
TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();
// We bind the prefHeight- and prefWidthProperty to the height and width of the stage.
table.prefHeightProperty().bind(stage.heightProperty());
table.prefWidthProperty().bind(stage.widthProperty());
stage.setScene(new Scene(table, 400, 400));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Create Tabel inside GridPane and Use GridePane inside AnchorPane.Click on GridPane(capture1).
Click on Ancho Pane Constraint inside the GridPane Layout (captur2).
In table view Layout select Hgrow and Vgrow as 'Always'(capture3)
VBox.setVgrow(tableView, Priority.ALWAYS);
OR for your parent layouts:
VBox.setVgrow({{PARENT}}, Priority.ALWAYS);
It fixed for me:
You could use a ScrollPane as the root of the scene and put everything else inside it. Then set the property setFitToWidth and setFitToHeight to true and all the content inside the ScrollPane will be stretched to fit the ScrollPane size and the ScrollPane will fit the Scene since its a Layout Pane. It will also show ScrollBars if the user resizes the window to be smaller than the contents minWidth, so the content doesnt get cut off!
#Override
public void start(Stage stage) {
TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();
table.setMinWidth(400);
ScrollPane sp = new ScrollPane(table);
sp.setFitToHeight(true);
sp.setFitToWidth(true);
stage.setScene(new Scene(table, 800, 600));
stage.show();
}
public static void main(String[] args) {
launch();
}
I copied parts of the MCVE From Jonathan's answer, hope you dont mind Jonathan :)
For more general tips for making resizable GUIs check this post!

How To Align Ok Button Of A Dialog Pane In Javafx?

I want to align i.e Position CENTER an OK button of a DialogPane. I have tried the below code but its not working.
Dialog dialog = new Dialog();
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.setStyle("-fx-background-color: #fff;");
// Set the button types.
ButtonType okButtonType = new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okButtonType, cancelButtonType);
dialogPane.lookupButton(cancelButtonType).setVisible(false);
// Testing
Button okButton = (Button) dialog.getDialogPane().lookupButton(okButtonType);
okButton.setAlignment(Pos.CENTER);
// End Testing
dialog.showAndWait();
Centering buttons in the ButtonBar of a Dialog is actually surprisingly difficult to achieve in a non-hacky way.
Below is the best solution I could come up with. It relies upon a dynamic CSS lookup of the HBox for the button container, to which it then adds a spacer region on the right to push the buttons to the left (the default ButtonSkin implementation already places an implicit spacer of the left which pushes the buttons to the right, which I determined using ScenicView). The combination of the left and right spacers end up aligning the buttons in the center. The solution also overrides the ButtonBar creation to stop the ButtonSkin internally reordering and performing additional layout of buttons, as, when it does that, you can't really reliably customize the layout yourself.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.Optional;
public class CenteredDialogButtons extends Application {
#Override
public void start(Stage stage) {
Button show = new Button("Show Dialog");
Dialog<ButtonType> dialog = new Dialog<>();
DialogPane dialogPane = new DialogPane() {
#Override
protected Node createButtonBar() {
ButtonBar buttonBar = (ButtonBar) super.createButtonBar();
buttonBar.setButtonOrder(ButtonBar.BUTTON_ORDER_NONE);
return buttonBar;
}
};
dialog.setDialogPane(dialogPane);
dialogPane.getButtonTypes().addAll(ButtonType.OK);
dialogPane.setContentText("Centered Button");
Region spacer = new Region();
ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
HBox.setHgrow(spacer, Priority.ALWAYS);
dialogPane.applyCss();
HBox hbox = (HBox) dialogPane.lookup(".container");
hbox.getChildren().add(spacer);
show.setOnAction(e -> {
Optional<ButtonType> result = dialog.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK) {
System.out.println("OK");
}
});
StackPane layout = new StackPane(
show
);
layout.setPadding(new Insets(50));
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The reason I don't quite like this solution is that the dynamic CSS lookups kind of violate API encapsulation, as the CSS structure of the JavaFX scene graphs for controls such as button bars is not really part of their public API. However, I don't think it is really possible to get centered buttons in a ButtonBar using the existing public APIs for JavaFX 8 and a default ButtonBar skin.
An alternate approach would be to create a custom skin for the ButtonBar associated with the dialog, but that approach is quite difficult and I wouldn't recommend it for this task.
Basically, the takeaway from all this is, just leave the default button layout and order for dialogs whenever you can, rather than trying to customize the dialog button layout. If you do want to have completely customized layout to the level of things like button placement, then you may be better off just creating your own custom dialog class by subclassing Stage rather than basing your custom dialog implementation on the in-built dialog class.
Related, but slightly different information is in:
Enter Key Event Is Not Working On Dialog In Javafx?
I tried to center OK button in Alert and I am not sure if this is bug or feature (Java8) but it was possible to center single button by setting new one:
alert.getButtonTypes().set(0, new ButtonType("OK", ButtonBar.ButtonData.LEFT));
As long as there is only one button with ButtonData.LEFT, it is centered in the middle of button panel. Obviously this solution does not work for panel with multiple buttons, but it might help to position single OK button.
Add this method to your code and call it when you need to align the buttons in a Dialog or Alert:
private void centerButtons(DialogPane dialogPane) {
Region spacer = new Region();
ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
HBox.setHgrow(spacer, Priority.ALWAYS);
dialogPane.applyCss();
HBox hboxDialogPane = (HBox) dialogPane.lookup(".container");
hboxDialogPane.getChildren().add(spacer);
}
Call it in this way: centerButtons(dialog.getDialogPane);
It's a kind of hack, but you could just do something like this:
okButton.translateXProperty().bind(okButton.prefWidthProperty().divide(-2));
The DialogPane is horizontal centered, so subtracting the okButton's half width will do the trick.
But I think this is a really dirty solution ;-)
Based on #ManuelSeiche's answer, here is how to compute exact distance to the center:
#FXML private Dialog<ButtonType> dialog;
#FXML private ButtonType btClose;
#FXML
private void initialize()
{
dialog.setOnShown(event ->
{
Platform.runLater(() ->
{
Button btnClose = (Button) dialog.getDialogPane().lookupButton(btClose);
HBox hBox = (HBox) btnClose.getParent();
double translateAmount = hBox.getWidth() / 2.0 - btnClose.getWidth() / 2.0 - hBox.getPadding().getLeft();
btnClose.translateXProperty().set(-translateAmount);
});
});
}

Resources