What's the code behind showAndWait in JavaFX? - java

I developed a small JavaFX application to be deployed in an Android device. Since, Alert is not yet supported in this current version of JavaFXPorts, I made my own implementaion of dialog. My problem is: I do not know how to implement the showAndWait functionality. Can someone know the idea?
Here's the code:
private static int status;
public static int showConfirm(String message){
status = 0;
black = new StackPane();
black.setStyle("-fx-background-color: black; -fx-opacity: 0.7;");
black.setPrefSize(Main.WIDTH, Main.HEIGHT);
Label label = new Label(message);
label.setStyle("-fx-font-size: 22px;");
label.setWrapText(true);
Button okBtn = new Button("OK");
okBtn.getStyleClass().add("terminal-button");
okBtn.setPrefWidth(120);
okBtn.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
status = 1;
Dialog.hide();
}
});
Button cancelBtn = new Button("Cancel");
cancelBtn.getStyleClass().add("terminal-button");
cancelBtn.setPrefWidth(120);
cancelBtn.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
status = -1;
Dialog.hide();
}
});
HBox btnContainer = new HBox(10);
btnContainer.setAlignment(Pos.CENTER_RIGHT);
btnContainer.getChildren().addAll(okBtn,cancelBtn);
VBox root = new VBox(30);
root.setStyle("-fx-background-color: white;");
root.setPadding(new Insets(20));
root.setPrefWidth(Main.WIDTH - 200);
root.getChildren().addAll(label,btnContainer);
Group container = new Group();
container.getChildren().add(root);
Main.PAGE.getChildren().add(black);
Main.PAGE.getChildren().add(container);
return status;
}

Related

Not able to click on Button JavaFX

I am creating a simple JavaFX based game and when I add a Button to my Pane and try to perform some action on it by clicking the mouse button while hovering over the button nothing happens - as if it is disabled but still visible.
private class Game extends Parent {
public Game() {
private Button newGameButton;
private Scene secondScene;
private Stage secondStage;
private Pane pane;
VBox menu = new VBox(15);
VBox highScore = new VBox(15);
menu.setTranslateX(280);
menu.setTranslateY(250);
highScore.setTranslateX(100);
highScore.setTranslateY(200);
try {
onLoad();
} catch (IOException e) {
e.printStackTrace();
}
newGameButton = new MenuButtonView("New Game");
newGameButton.setOnMouseClicked(event -> {
pane = new Pane();
secondScene = new Scene(pane, 800, 600);
secondStage = new Stage();
secondStage.setScene(secondScene);
secondStage.show();
scoreAndCrackView();
mickeyView();
});
public void mickeyView(){
private Button leftDownRedButton;
leftDownRedButton = new Button();
rightDownRedButton.setTranslateX(640);
rightDownRedButton.setTranslateY(560);
pane.getChildren().add(rightDownRedButton);
leftDownRedButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
System.out.println("Clicked");
}
});
public void scoreAndCrackView()
{
vertBox = new VBox();
vertBox.setPrefSize(800, 100); // this one was causing issue, previously: vertBox.setPrefSize(800, 600)
vertBox.getChildren().addAll(scoreLabel,crackLabel);
pane.getChildren().add(vertBox);
}
}
UPDATE
Btw I found the cause of the error - as you guys suggested something was covering my buttons and more precisely the VBox in another method which was set to the whole screen. After changing the values and minimizing prefWidth and prefHeight I can click on the buttons. Lesson for the future to set the Box only for the required area.

JavaFX switching scenes

I've been trying to make my application to switch between scenes. Here is a copy of part of the code. The credits scene simply has a back button which should return me to the main scene.
When I try to click on credits button on main scene it is becoming white a white screen. I believe that there is a better way to solve this problem could you give me some advices ?
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(GUI.class);
}
}
public class GUI extends Application {
#Override
public void start(Stage primaryStage) {
Scene mainScene, creditsScene = null;
mainScene = getMainScene(primaryStage, creditsScene);
creditsScene = getCreditsScene(primaryStage, mainScene);
primaryStage.setTitle("Test application");
primaryStage.setScene(mainScene);
primaryStage.show();
}
private Scene getMainScene(Stage primaryStage, Scene creditsScene) {
final Button credits = new Button("Credits");
credits.setOnAction((ActionEvent e) -> {
primaryStage.close();
primaryStage.setScene(creditsScene);
primaryStage.show();
});
VBox x = new VBox(50);
x.setAlignment(Pos.CENTER);
x.getChildren().addAll( run, displayInfo,
label1, displayInfo, textField, submitName, credits, exit);
//scene size
Scene scene = new Scene(x, 650, 900);
return scene;
}
private Scene getCreditsScene(Stage primaryStage, Scene main) {
final Button back = new Button("Back");
back.setOnAction((ActionEvent e) -> {
primaryStage.setScene(main);
});
VBox x = new VBox(50);
x.getChildren().addAll(back);
Scene credits = new Scene(x, 650, 900);
return credits;
}
Try to switch order of strings:
mainScene = getMainScene(primaryStage, creditsScene);
creditsScene = getCreditsScene(primaryStage, mainScene);
here you pass to getMainScene null.

How do I display a popup while I'm on the primary stage

I tried using this method to print show a popup with label "THAT'S IT" and I don't want to use the Popup class
public void showStage(Stage Owner){
HBox hBox = new HBox();
hBox.getChildren().add(new Label("THAT'S IT"));
Scene sc = new Scene(hBox);
Stage popup = new Stage();
popup.setScene(sc);
popup.setWidth(400);
popup.setHeight(100);
popup.initOwner(owner);
popup.initModality(Modality.WINDOW_MODAL);
popup.show();
}
and then I call the showStage() method from the start method
public void start(Stage primaryStage) {
Label lb = new Label();
btn.setText("Say 'Hello World'");
btn.setOnAction(e->{
lb.setText("hello everyone");showStage(primaryStage);
});
But the output of the code :
Why don't you use a dialog?
You can use it in your main controller class without creating an other stage for instance like this:
Dialog dialogQtPrescription = new Dialog();
dialogQtPrescription.setTitle("yourTitle");
dialogQtPrescription.setHeaderText("yourHeadertext");
dialogQtPrescription.initModality(Modality.WINDOW_MODAL);
dialogQtPrescription.initOwner(mainStage);
dialogQtPrescription.initStyle(StageStyle.UTILITY);
GridPane gridDialogPrescription = new GridPane();
gridDialogPrescription.setHgap(10);
gridDialogPrescription.setVgap(10);
gridDialogPrescription.add(new Label(bundle.getString("quantityPrescription.title")), 0, 0);
TextField txtQtPrescr = new TextField();
ButtonType buttonTypeNo = new ButtonType("no");
ButtonType buttonTypeYes = new ButtonType("yes");
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
dialogQtPrescription.getDialogPane().getButtonTypes().addAll(buttonTypeNo,buttonTypeYes, buttonTypeCancel);
txtQtPrescr.setPrefWidth(100);
gridDialogPrescription.add(txtQtPrescr, 1, 0);
dialogQtPrescription.getDialogPane().setContent(gridDialogPrescription);
Optional<ButtonType> result = dialogQtPrescription.showAndWait();
this is just a stack of code from a project but i hope it make you to understand my idea.
here's better explained: http://code.makery.ch/blog/javafx-dialogs-official/
You can use this in order to make a Popup on any Screen in JavaFX
public void popup() {
final Stage dialog = new Stage();
dialog.setTitle("Confirmation");
Button yes = new Button("Yes");
Button no = new Button("No");
Label displayLabel = new Label("What do you want to do ?");
displayLabel.setFont(Font.font(null, FontWeight.BOLD, 14));
dialog.initModality(Modality.NONE);
dialog.initOwner((Stage) tableview.getScene().getWindow());
HBox dialogHbox = new HBox(20);
dialogHbox.setAlignment(Pos.CENTER);
VBox dialogVbox1 = new VBox(20);
dialogVbox1.setAlignment(Pos.CENTER_LEFT);
VBox dialogVbox2 = new VBox(20);
dialogVbox2.setAlignment(Pos.CENTER_RIGHT);
dialogHbox.getChildren().add(displayLabel);
dialogVbox1.getChildren().add(yes);
dialogVbox2.getChildren().add(no);
yes.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
// inside here you can use the minimize or close the previous stage//
dialog.close();
}
});
no.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
dialog.close();
}
});
dialogHbox.getChildren().addAll(dialogVbox1, dialogVbox2);
Scene dialogScene = new Scene(dialogHbox, 500, 40);
dialogScene.getStylesheets().add("//style sheet of your choice");
dialog.setScene(dialogScene);
dialog.show();
}

Sidescrolling over image in JavaFX

I've wrapped my brain around a challenge for 2 days now. I am all empty for ideas, so I hope someone out there know how to do this.
I got inspired by Angela Caicedo's city app, from the website https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx, and trying to make a similar app-gui to show available rooms and lecture halls at my University.
I am using Java FX to build the gui, and I get the whole GUI printed out, which is a java fx pane with a image on it. What I want, however, is to just see a small part of the gui (the backgroundimage I am using is w:1500px h:500, so each part will be w:500px h:500px), then be able to push a button or a arrow (or similar) to move the window to the next step. On top of the image there is 3 panes with w:500px h:500px snapped to each other. Maybe this is a bad solution, considering all the pane-types Java FX has available.
So, what I need is a constrained viewer of sorts.
I've also used FMXL to build the GUI, having one FMXL document, one Controller and a css-file to handle the design.
I'm sure I've been everywhere on the internet by now, so I really hope someone has done this before in Java FX :)
Ok, here is some code example. The first sample works nice, but I want to implement the second example instead. I am reading on the TranslateTransition of JavaFX, but my efforts of trying to switch the code is hopeless..
1'st example (working, and is fading in and out of the fxml screen):
public boolean setScreen(final String name){
if (screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
if (!getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(2000), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
getChildren().remove(0); //remove the displayed screen
getChildren().add(0, screens.get(name)); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2000), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
setOpacity(0.0);
getChildren().add(screens.get(name)); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(1000), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}
}
Second example, the TranslateTransition I want to implement instead:
private final double IMG_WIDTH = 500;
private final double IMG_HEIGHT = 500;
private final int NUM_OF_IMGS = 3;
private final int SLIDE_FREQ = 4; // in secs
#Override
public void start(Stage stage) throws Exception {
stage.initStyle(StageStyle.UNDECORATED);
StackPane root = new StackPane();
Pane clipPane = new Pane();
// To center the slide show incase maximized
clipPane.setMaxSize(IMG_WIDTH, IMG_HEIGHT);
clipPane.setClip(new Rectangle(IMG_WIDTH, IMG_HEIGHT));
HBox imgContainer = new HBox();
ImageView imgGreen = new ImageView(new Image(getClass().getResourceAsStream("uib_01.jpg")));
ImageView imgBlue = new ImageView(new Image(getClass().getResourceAsStream("uib_02.jpg")));
ImageView imgRose = new ImageView(new Image(getClass().getResourceAsStream("uib_03.jpg")));
imgContainer.getChildren().addAll(imgGreen, imgBlue, imgRose);
clipPane.getChildren().add(imgContainer);
root.getChildren().add(clipPane);
Scene scene = new Scene(root, IMG_WIDTH, IMG_HEIGHT);
stage.setTitle("Image Slider");
stage.setScene(scene);
startAnimation(imgContainer);
stage.show();
}
private void startAnimation(final HBox hbox) {
EventHandler<ActionEvent> slideAction = (ActionEvent t) -> {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
EventHandler<ActionEvent> resetAction = (ActionEvent t) -> {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1), hbox);
trans.setByX((NUM_OF_IMGS - 1) * IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
List<KeyFrame> keyFrames = new ArrayList<>();
for (int i = 1; i <= NUM_OF_IMGS; i++) {
if (i == NUM_OF_IMGS) {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), resetAction));
} else {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), slideAction));
}
}
Timeline anim = new Timeline(keyFrames.toArray(new KeyFrame[NUM_OF_IMGS]));
anim.setCycleCount(Timeline.INDEFINITE);
anim.playFromStart();
}
The screen should change on button click. I have this in a separate controller class:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class roomAppController implements Initializable, ScreenController {
private ScreenPane myScreenPane;
#FXML
public ImageView bldArw_1;
public ImageView rmArw_1;
#FXML
private void handleExitButtonEvent(MouseEvent e) {
System.out.println("Button is clicked");
System.exit(0);
}
#FXML
private void handleNextPageEvent(MouseEvent e) {
if((ImageView)e.getSource() == bldArw_1) {
myScreenPane.setScreen("buildingScreen");
}
if((ImageView)e.getSource() == rmArw_1) {
myScreenPane.setScreen("roomScreen");
}
System.out.println("Clicked");
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#Override
public void setScreenPane(ScreenPane screenPage) {
myScreenPane = screenPage;
}
}

JAVAFX:Create stage and text area at runtime

I am new to JavaFX, here I want to create a new Stage and one TextArea inside it at the run-time and I want to pass a line to that text area and update it continuously.
Can anybody please give me the example of doing this?
Hyperlink link = new Hyperlink("TEST");
link.setOnAction(new EventHandler<ActionEvent>() {
#override public void handle(ActionEvent e) {
Stage stage = new Stage();
TextArea text = new TextArea():
VBox vbox = new VBox();
Button close = new Button();
close.setText("Close");
close.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
stage.close();
}
});
vbox.getChildren().addAll(text, close);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setMinWidth(100);
stage.setMinHeight(100);
stage.show();
// ...
text.setText("update");
}
});

Categories

Resources