I have an application in JavaFX FXML by using Model View Controller. I want to move some sliders with keyboard. To do this in the main class I put a KeyEvent to hear what happens on the keyboard. In the controller class FXMLDocumentController where are FXML variables. These variables are passed to a third class. Where there sliders are changed when you click any.
The problem is that when I pass the variables of the sliders in the third class are perfectly stored but when you run the code to modify sliders coming past the main class when clicked are FXML variables are null.
Here you have the code:
Main class:
public class OpenPilot extends Application {
Movements Movements = new Movements();
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent Key) {
Movements.GetKeys(Key);
}
});
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Controller:
public class FXMLDocumentController implements Initializable {
Movements Movements = new Movements();
#FXML public Slider SpeedSlider;
#FXML public Slider TurnsSlider;
#Override
public void initialize(URL url, ResourceBundle rb) {
//Send GUI Information
Movements.GetSliders(SpeedSlider, TurnsSlider);
}
}
Movements:
public class Movements {
//Define Data Variables
public double SpeedValue;
public double TurnsValue;
//Define GUI Variables
private Slider SpeedSlider;
private Slider TurnsSlider;
public void GetSliders(Slider SpeedSlider, Slider TurnsSlider) {
this.SpeedSlider = SpeedSlider;
this.TurnsSlider = TurnsSlider;
}
//Get Sliders
public void GetKeys(KeyEvent Key) {
System.out.println(Key.getCode());
System.out.println(SpeedSlider);
Platform.runLater(new Runnable() {
#Override public void run() {
TurnsSlider.setValue(10);
}
});
}
}
You use 2 different instances of the Movements class (Movements Movements = new Movements(); in OpenPilot and FXMLDocumentController). Since you don't use static fields / methods, you won't get any data from one instance to the other. You have to get the Movements object from the controller:
Controller:
public class FXMLDocumentController implements Initializable {
Movements movements = new Movements();
public Movements getMovements() {
return movements;
}
#FXML public Slider SpeedSlider;
#FXML public Slider TurnsSlider;
#Override
public void initialize(URL url, ResourceBundle rb) {
//Send GUI Information
movements.GetSliders(SpeedSlider, TurnsSlider);
}
}
Use a instance of the FXMLLoader instead of the static method to get the Movements field from the controller:
Main class:
public class OpenPilot extends Application {
Movements movements;
#Override
public void start(Stage stage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader();
// use non-static load method here
Parent root = fxmlLoader.load(getClass().getResource("FXMLDocument.fxml").openStream());
// get movements from via controller
FXMLDocumentController controller = fxmlLoader.<FXMLDocumentController>getController();
movements = controller.getMovements();
Scene scene = new Scene(root);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent Key) {
movements.GetKeys(Key);
}
});
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Related
I'm making an application with JavaFX and Scene Builder.
I have two controllers:Controller and FontController
I have Main class that launch my program and open Stage with first fontroller (Controller)
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
Parent root = FXMLLoader.load(getClass().getResource("/card/card.fxml"));
Scene scene = new Scene(root, 1600, 600);
primaryStage.setScene(scene);
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setMaximized(true);
primaryStage.setResizable(true);
primaryStage.getIcons().add(new Image("card/resources/logo-icon.png"));
primaryStage.show();
//adding resize and drag primary stage
ResizeHelper.addResizeListener(primaryStage);
//assign ALT+ENTER to maximize window
final KeyCombination kb = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (kb.match(event)) {
primaryStage.setMaximized(!primaryStage.isMaximized());
primaryStage.setResizable(true);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
There is a label and a button in Controller. When I click on the button a method is called and new window with second controller appears(FontController):
#FXML private Button btnFont;
#FXML private Label category1
#FXML
void changeFont(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new
FXMLLoader(getClass().getResource("font.fxml"));
Parent rootFont = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setTitle("Select Font");
stage.setScene(new Scene(rootFont));
stage.show();
} catch (Exception e) {
System.out.println("can't load new window");
}
}
There is the button "OK" and label in FontCOntroller:
#FXML private Label fontLabel;
#FXML private Button btnFontOk;
Please tell me, what should I do to send and apply text from label in FontController when I click on the burtton "OK" to label in Controller?
SOLUTION FOUND:
I created class "Context" in my project directory to make all controllers communicate each other. You can add as many controllers as you want there.
Here it looks like:
package card;
public class Context {
private final static Context instance = new Context();
public static Context getInstance() {
return instance;
}
private Controller controller;
public void setController(Controller controller) {
this.controller=controller;
}
public Controller getController() {
return controller;
}
private FontController fontController;
public void setFontController(FontController fontController) {
this.fontController=fontController;
}
public FontController getFontController() {
return fontController;
}
}
Controller:
I created getters and setters (ALT + Insert in IDEA) for Label that I wanna change
public Label getCategory1() {
return category1;
}
public void setCategory1(Label category1) {
this.category1 = category1;
}
To get FontController variables and methods through Context class I placed line of code
//getting FontController through Context Class
FontController fontCont = Context.getInstance().getFontController();
I registered Controller in Context class through my initialize method (my class implements Initializable)
#FXML
public void initialize(URL location, ResourceBundle resources) {
//register Controller in Context Class
Context.getInstance().setController(this);
}
FontController:
to get Controller variables and methods I placed this code:
//getting Controller variables and methods through Context class
Controller cont = Context.getInstance().getController();
I also registered FontController in Context class through initialize method:
#Override
public void initialize(URL location, ResourceBundle resources) {
//register FontController in Context Class
Context.getInstance().setFontController(this);
}
Method that send text and text color from label in this FontController to label in Controller when I click on button:
#FXML
void applyFont(ActionEvent event) {
cont.getCategory1().setText(fontLabel.getText());
cont.getCategory1().setTextFill(fontLabel.getTextFill());
}
*By creating Context class you can make controllers communicate each other and create as many controllers as you want there. Controllers see variables and methods of each other
Every time I ran JavaFX app I encounter the error below.
15:11:52.778 [JavaFX Application Thread] ERROR org.fhl.Manifesto - javafx.fxml.LoadException:
/C:/ManGenFX/target/classes/dataController.fxml
/C:/ManGenFX/target/classes/ManifestoMain.fxml:7
But it only happens if I add the initialize method on Main Controller.
public class MainController{
#FXML
GenerateController genCont;
#FXML
private Pane generatePane;
#FXML
AnchorPane mainFx;
private Node source;
//Other Button, TextFields and Labels declaration
#FXML
private void browseFile(ActionEvent x) {
//Browse file definition
}
#FXML
private void savePath(ActionEvent x) {
//Save file definition
}
//Problem with this method
#FXML
public void initialize() {
System.out.println("Initialize generate controller panel");
logger.info("Initialize generate controller panel");
genCont.init(this);
}
}
If I remove the initialize method on MainController class it will not throw any error but nothing happens either if I click on the generate button which is defined in GenerateController class below.
public class GenerateController {
#FXML
Button btnGenerate;
#FXML
Pane paneGen;
#FXML
public void generateMan(ActionEvent event) {
//generateMan body when Generate button is clicked
}
public void init(MainController mc) {
System.out.println("Init mainControl");
mainControl = mc;
}
public void validate() {
//Definition of method body here
}
}
This is the main Class
public class Man extends Application {
private Stage mainStage;
#Override
public void start(Stage primaryStage) {
this.mainStage = primaryStage;
this.mainStage.setTitle("Manifest");
try{
Parent root = FXMLLoader.load(getClass().getResource("/ManifestoMain.fxml"));
Scene sMain = new Scene(root);
mainStage.setScene(sMain);
mainStage.show();
}catch(IOException ioE) {
logger.error(ioE);
}
}
public static void main(String[] args) {
launch(args);
}
}
Also, I placed my dataController.fxml, ManifestoMain.fxml, and generateView.fxml under resources folder but it don't have any problem accessing the files. Appreciate help on this.
I have created two java classes which have a static method which returns an AnchorPane after setting all properties of required labels and buttons.
For example:
class HomePageScene {
static AnchorPane getHomePageScene() {
//some code
//a button which is to be clicked to go to Login Page
//some code
}
}
class LoginPageScene {
static AnchorPane getLoginPageScene() {
//some code
}
}
And there is another class which has the main().
public class JavaFXEventDemo extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage myStage) {
myStage.setTitle("Program Windiw");
AnchorPane HomePane = HomePageScene.getHomePageScene();
AnchorPane LoginPane = LoginPageScene.getLoginPageScene();
Scene HomePage = new Scene(HomePane, 400.0, 300.0);
Scene LoginPage = new Scene(LoginPane, 400.0, 300.0);
myStage.setScene(HomePage);
myStage.show();
}
}
First I set the HomePage as the scene on the stage. In the screen there is a button, which when I click, I want the scene to the LoginPage. How do I do this?
All the three classes are in different files.I tried setting onAction() method, but in that, handle() method's return type is void, whereas I need to return an AnchorPane.
Bind a function for your button (onAction). In this function, call a function in your main class which will load the scene you want (void javafx.scene.Scene.setRoot(Parent value)) ?
EDIT:
What I meant :
public class JavaFXEventDemo extends Application {
private static Scene HomePage;
private static Scene LoginPage;
private static Stage myStage;
public static void main(String[] args) {
launch(args);
}
public void start(Stage myStage) {
JavaFXEventDemo.myStage = myStage;
myStage.setTitle("Program Windiw");
AnchorPane HomePane = HomePageScene.getHomePageScene();
AnchorPane LoginPane = LoginPageScene.getLoginPageScene();
HomePage = new Scene(HomePane, 400.0, 300.0);
LoginPage = new Scene(LoginPane, 400.0, 300.0);
loadHomePage();
myStage.show();
}
public static void loadHomePage(){
JavaFXEventDemo.myStage.setScene(HomePage);
}
public static void loadLoginPage(){
JavaFXEventDemo.myStage.setScene(LoginPage);
}
}
And just call loadXXXXPage() on your button.
So I've been trying to do this for atleast 4 hours now and with no succes.
The case: I need to open a new FXML Window after pressing a button on my Controller class.
I'm using JavaFX for this.
We are working in packages like this.
lobby.gui, login.gui etc...
It doesn't give an error message but the Scene will not start.
This is the LoginFXController where the button is pressed.
public class LoginFXController implements Initializable
{
DatabaseMediator mediator;
//INLOGGUI FXML
#FXML TextField tf_inlogusername;
#FXML PasswordField pf_inlogpassword;
#FXML Button btn_inlog;
#FXML Button btn_register;
#Override
public void initialize(URL url, ResourceBundle rb)
{
mediator = new DatabaseMediator();
}
public void loginPersoon(Event event)
{
String gebruikersnaam = tf_inlogusername.getText();
String wachtwoord = pf_inlogpassword.getText();
Persoon p = new Persoon(gebruikersnaam, wachtwoord);
Boolean check = mediator.controleerPersoonsGegevens(gebruikersnaam, wachtwoord);
if(check == false)
{
showDialog("Error", "Gegevens komen al voor in het Systeem!");
}
else
{
showDialog("Succes", "Welkom: " + gebruikersnaam);
try
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("lobby.gui/LobbyGUI.fxml"));
LobbyGUI controller = new LobbyGUI();
loader.setController(controller);
loader.setRoot(controller);
Parent root = (Parent)loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
}
catch(IOException e)
{
showDialog("Error", e.getMessage());
}
}
}
And I'm trying to fire of this new class
public class LobbyGUI extends Application
{
#Override
public void start(Stage stage) throws IOException
{
Parent root = FXMLLoader.load(getClass().getResource("LobbyGUI.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
I'm trying to find a way to access the Stage in my main JavaFx class from another class so I can perform some actions on it but I can't since it is passed as a parameter like so:
#Override
public void start(final Stage primaryStage) {
The WakiliProject Class in full:
public class WakiliProject extends Application {
#Override
public void start(final Stage primaryStage) {
Group root = new Group();
StageDraggable.stageDraggable(root, primaryStage);
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root, 900, 654);
primaryStage.setScene(scene);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setTitle("Wakili");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
How can I catch the above Stage primaryStage from another Class and do some actions like I do below after initializing the Stage `public Stage newTryEMail;':
public class TryEMailController implements Initializable {
// Initializes the controller class.
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public Stage newTryEMail;
public void newTryEMailStage() throws IOException {
newTryEMail = new Stage();
newTryEMail.initModality(Modality.WINDOW_MODAL);
newTryEMail.initOwner(AddNewEmailController.newComposeNewEmail);
Parent newTryEMailRoot = FXMLLoader.load(getClass().getResource("/wakiliproject/Forms/AddNew/NewEmail/TryEMailController.fxml"));
StageDraggable.stageDraggable(newTryEMailRoot, newTryEMail);
Scene newComposeNewEmailScene = new Scene(newTryEMailRoot, 590, 670);
newTryEMail.setScene(newComposeNewEmailScene);
newTryEMail.show();
}
}
from another class called TryEMailController?
Thank you all in advance.
Try it like this:
public void newTryEMailStage(Stage primaryStage) throws IOException {
newTryEMail = primaryStage;
And in the start method:
newTryEMailStage(primaryStage);
You pass the primaryStage reference from the start() method to the class that you want to have access to it. Then you store a reference to the primaryStage object in the class that you want to have access to it. If you are trying to "catch" the reference to the primaryStage object prior to the start() method running, there is no way I know of to do that. So organize your code accordingly.