kinansaeb
kinansaeb

Reputation: 43

JavaFX 8 on Button Click show other Scene

Hello I am currently working on a PIN Generator for my work and as I am completely new to Java I am having a few difficulties, especially when using JavaFX. I want to make the programm show another .fxml file when clicking on one of each buttons.

Here is my code:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
    public static void main(String[] args) {
        Application.launch(main.class, args);
    }
        @Override
        public void start(Stage stage) throws Exception {
            Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));

            stage.setTitle("PIN-Generator");
            stage.setScene(new Scene(root, 600, 400));
            stage.show();
        }
    }

I have created a controller Class for each button on the scene.

Controller Class Code:

    package view;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

public class MainController {

    @FXML
    private Label dpmadirektpropingenerator;
    @FXML
    private Button unlockPinButton;
    @FXML
    private Button confirmationPinButton;
}

Upvotes: 1

Views: 9193

Answers (1)

Mohammad Sianaki
Mohammad Sianaki

Reputation: 1771

This code should works.
Modify your main class like this:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
public static void main(String[] args) {
    Application.launch(main.class, args);
}
    static Stage stg;
    @Override
    public void start(Stage stage) throws Exception {
    this.stg = stage;
        Parent root = FXMLLoader.load(getClass().getResource("/view/main.fxml"));
        stage.setTitle("PIN-Generator");
        stage.setScene(new Scene(root, 600, 400));
        stage.show();
    }
}

and here is your pressButton function:

 public void pressButton(ActionEvent event){               
    try {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("sedondFXML.fxml"));
            Parent root = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root));  
            stage.show();
            main.stg.close();
    } catch(Exception e) {
       e.printStackTrace();
      }
 }

Upvotes: 1

Related Questions