Not able to click on Button JavaFX - java

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.

Related

How to check is mouse cursor is on the button in Java FX?

I'm new to Java and I'm wondering if it is possible to check if mouse cursor is for example on the button? I mean not getting clicking events but just moving cursor on the button.
I had working code getting click and then printing something, but I want to change it a little and I can't find out why it doesn't work.
public class Main extends Application implements EventHandler<MouseEvent> {
Button button;
Stage window;
Scene scene;
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Where's the button?");
button.setText("Click me!");
button.setOnMouseMoved(this);
StackPane layout = new StackPane();
layout.getChildren().add(button);
Scene scene = new Scene(layout, 300,350);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
#Override
public void handle(MouseEvent actionEvent) {
System.out.println("You clicked the button!");
}
}
I have made small code for you. Take a look. It prints in the console "Ho-Ho-Ho-Hovereed!" once you hover over your button.
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Hover over me.'");
btn.hoverProperty().addListener((event)->System.out.println("Ho-Ho-Ho-Hovereeed!"));
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Mouse manpulation example in JavaFX!");
primaryStage.setScene(scene);
primaryStage.show();
}
i guess you can do that with event handler or css, like...
button.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
System.out.println("Cursor Over Button");
}
});
or/with styles (css)
.button:hover{
-fx-background-color: red;
}
Each Node provides a hover property to track whether the mouse cursor is hovering over it or not. By using a simple listener, you can detect when the mouse starts and stops hovering:
button.hoverProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
System.out.println("Hovering...");
} else {
System.out.println("Retreating...");
}
});
With this listener, newValue will always be true if the mouse is currently hovering over the button and change to false when the mouse leaves the area.
There is also a useful check on a Node - isHover() You can use it on MouseEvents to check if the mouse is hovering over the needed node. Such a tip ;)
button.setOnMouseEntered( (event ) -> {
button.setTranslateX(button.getTranslateX() + 20);
button.setTranslateY(button.getTranslateY() + 20);
});`
Replace button.setOnMouseMoved(this); with my code. This will do!

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 to add a button to another class

I have a class called Restaurant, that has an FXML file, in that class, I have a button that when pressed opens another window called tables, that also has an FXML file, I have a minimize button in tables window.
What I want is when I press the minimize button in table, a new button will be added to the Restaurant window.
But I'm getting a null exception.
Can someone help me solve this.
This is the code for my minimize button:
#FXML
public void minimiza(ActionEvent event) {
Button Tables = new Button("Mesas");
try {
Stage mesa = (Stage) ((Button) event.getSource()).getScene().getWindow();
mesa.setIconified(true);
FXMLLoader loader = new FXMLLoader();
RestauranteController controle = loader.getController();
controle.adicionaBotao(Tables);
} catch (Exception e) {
System.out.println("Not working " + e.getMessage());
}
}
It's probably better to just listen to the iconified property of the Stage from the Restaurant class. If the minimized state does not match the iconified state, you could create this property in the controller for the tables window yourself.
private int windowCount;
#Override
public void start(Stage primaryStage) {
Button btn = new Button("Show new Window");
VBox buttonContainer = new VBox(btn);
btn.setOnAction((ActionEvent event) -> {
// create new window
windowCount++;
Label label = new Label("Window No " + windowCount);
Stage stage = new Stage();
Scene scene = new Scene(label);
stage.setScene(scene);
// button for restoring from main scene
Button restoreButton = new Button("Restore Window " + windowCount);
// restore window on button click
restoreButton.setOnAction(evt -> {
stage.setIconified(false);
});
// we rely on the minimize button of the stage here
// listen to the iconified state to add/remove button form main window
stage.iconifiedProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
buttonContainer.getChildren().add(restoreButton);
} else {
buttonContainer.getChildren().remove(restoreButton);
}
});
stage.show();
});
Scene scene = new Scene(buttonContainer, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
BTW: Note that without loading a fxml, FXMLLoader will never create a controller instance, let alone without the fxml being specified. Furthermore under no circumstances would it return the same controller instance as the one used with your Restaurant window.

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;
}
}

Resize JavaFX tab when double click

I have this simple example with JavaFX tabs:
public class test extends Application
{
private BorderPane root;
// Navigation Utilization
private ActionTabs actiontabs;
#Override
public void start(Stage primaryStage)
{
// Set Main Window Label
primaryStage.setTitle("Desktop Client");
Image iv = new Image(getClass().getResource("/images/internet-icon.png").toExternalForm());
primaryStage.getIcons().add(iv);
root = new BorderPane();
root.setLeft(getLeftHBox(primaryStage, root));
Scene scene = new Scene(root, 1000, 1000, Color.WHITESMOKE); // Set main Stage color
primaryStage.setScene(scene);
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
// Set Stage boundaries to visible bounds of the main screen
primaryStage.setX(primaryScreenBounds.getMinX());
primaryStage.setY(primaryScreenBounds.getMinY());
primaryStage.setWidth(primaryScreenBounds.getWidth()); // Maximum width of the display
primaryStage.setHeight(primaryScreenBounds.getHeight()); // Maximum height of the display
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
private HBox getLeftHBox(Stage primaryStage, BorderPane root)
{
HBox hbox = new HBox();
TabPane tabPane = new TabPane();
BorderPane mainPane = new BorderPane();
tabPane.setStyle("-fx-font-size: 12pt;"); // Set global size for the font
// Create Tabs
Tab tabA = new Tab();
tabA.setText("Main Component");
tabA.setStyle("-fx-font-size: 12pt;"); // Set size of the tab name
tabA.setClosable(false);
// Add something in Tab
StackPane tabA_stack = new StackPane();
tabA_stack.setAlignment(Pos.CENTER);
tabA_stack.getChildren().add(new Label("Label#Tab A"));
tabA.setContent(tabA_stack);
tabPane.getTabs().add(tabA);
Tab tabB = new Tab();
tabB.setText("Second Component");
tabB.setStyle("-fx-font-size: 12pt;"); // Set size of the tab name
tabB.setClosable(false);
// Add something in Tab
StackPane tabB_stack = new StackPane();
tabB_stack.setAlignment(Pos.CENTER);
tabB_stack.getChildren().add(new Label("Label#Tab B"));
tabB.setContent(tabB_stack);
tabPane.getTabs().add(tabB);
Tab tabC = new Tab();
tabC.setText("Last Component");
tabC.setStyle("-fx-font-size: 12pt;"); // Set size of the tab name
tabC.setClosable(false); // da se mahne opciqta da se zatvarq tab
// Add something in Tab
StackPane tabC_vBox = new StackPane();
tabC_vBox.setAlignment(Pos.CENTER);
tabC_vBox.getChildren().add(new Label("Label#Tab C"));
tabC.setContent(tabC_vBox);
tabPane.getTabs().add(tabC);
mainPane.setCenter(tabPane);
mainPane.setPrefSize(300, 500);
//mainPane.setLayoutX(5); // Horizontal Position
mainPane.setLayoutY(32); // Vertical Position
hbox.getChildren().addAll(mainPane);
return hbox;
}
}
I want when I double click on a tab name to maximize the size of the body of the tab and make it the same width and height as the size of the application. Similar for example to Eclipse IDE tabs. Is this possible with JavaFX?
EDIT
This is the code that I have tested.
public BorderPane initNavigation(Stage primaryStage)
{
VBox stackedTitledPanes = createStackedTitledPanes();
ScrollPane scroll = makeScrollable(stackedTitledPanes);
final TabPane tabPane = new TabPane();
final BorderPane mainPane = new BorderPane();
final Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
tabPane.setStyle("-fx-font-size: 12pt;"); // Set global size for the font
// Create Tabs
Tab tabA = new Tab();
tabPane.setOnMouseClicked(new EventHandler<MouseEvent>()
{
private double sizeX, sizeY;
private boolean first = true;
#Override
public void handle(MouseEvent me)
{
if (first)
{
sizeX = mainPane.getWidth();
sizeY = mainPane.getHeight();
first = false;
}
if (me.getButton().equals(MouseButton.PRIMARY) && me.getClickCount() % 2 == 0)
{
if (sizeX != mainPane.getWidth() || sizeY != mainPane.getHeight())
{
mainPane.setPrefSize(sizeX, sizeY);
}
else
{
mainPane.setPrefSize(primaryScreenBounds.getWidth(), primaryScreenBounds.getHeight());
//mainPane.toFront();
}
}
}
});
tabA.setText("Main Component");
tabA.setContextMenu(makeTabContextMenu(tabA, tabPane)); // Set right mouse click menu
// Add something in Tab
StackPane tabA_stack = new StackPane();
tabA_stack.setAlignment(Pos.CENTER);
tabA_stack.getChildren().add(scroll);
tabA.setContent(tabA_stack);
tabPane.getTabs().add(tabA);
Tab tabB = new Tab();
tabB.setText("Second Component");
tabB.setContextMenu(makeTabContextMenu(tabB, tabPane)); // Set right mouse click menu
// Add something in Tab
StackPane tabB_stack = new StackPane();
tabB_stack.setAlignment(Pos.CENTER);
tabB_stack.getChildren().add(new Label("Label#Tab B"));
tabB.setContent(tabB_stack);
tabPane.getTabs().add(tabB);
Tab tabC = new Tab();
tabC.setText("Last Component");
tabC.setContextMenu(makeTabContextMenu(tabC, tabPane)); // Set right mouse click menu
// Add something in Tab
StackPane tabC_vBox = new StackPane();
tabC_vBox.setAlignment(Pos.CENTER);
tabC_vBox.getChildren().add(new Label("Label#Tab C"));
tabC.setContent(tabC_vBox);
tabPane.getTabs().add(tabC);
mainPane.setCenter(tabPane);
mainPane.setPrefSize(300, 500);
//mainPane.setLayoutX(5); // Horizontal Position
mainPane.setLayoutY(32); // Vertical Position
scroll.setPrefSize(395, 580);
scroll.setLayoutX(5);
scroll.setLayoutY(32);
return mainPane;
}
The problem is how I can cover the stage with the tab code when I double click on the tab name?
You required to add few lines to your code, here is a sample for you,
.....
Tab tabA = new Tab();
Label tabALabel = new Label("Main Component");
tabA.setGraphic(tabALabel);
tabALabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
mainPane.setPrefSize(500, 500); //Your required size
}
}
}
});
....
Try this, and tell if there's any difficulty.
You could create another BorderPane which contains your root = new BorderPane();
in Center, and replace it with the Tabpanel on doubleclick.
Resulting in:
rootRoot = new BorderPane();
BorderPane root = new BorderPane();
root.setLeft(getLeftHBox(primaryStage, root));
rootRoot.setCenter(root);
Scene scene = new Scene(rootRoot, 1000, 1000, Color.WHITESMOKE); // Set main Stage color
with "rootRoot" being the new root (great Name, i know ^^), and
Label tabALabel=new Label("Label#Tab A");
tabALabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
//mainPane.setPrefSize(500, 500); //Your required size
rootRoot.setCenter(mainPane);
}
}
}
});
for maximizing.

Categories

Resources