How to get the controller of an included FXML? - java

I have a simple two tab application build around JavaFXML and scenebuilder. The tabs do nothing at present because I cannot get past a nullpointer exception when trying to load them.
The java and fxml files are arranged in a Netbeans project like this:
Main Application: The application main class MainApp.java sets the scene and is declared as follows:
package tabpane;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class MainApp extends Application {
private static Stage primaryStage;
private AnchorPane rootLayout;
public MainApp() {}
#Override
public void start(Stage primaryStage) {
primaryStage.initStyle(StageStyle.UNDECORATED);
MainApp.primaryStage = primaryStage;
MainApp.primaryStage.setTitle("Account Names");
initRootLayout();
}
public void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/MainView.fxml"));
rootLayout = (AnchorPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, e);
System.out.println("MainApp: IOException in method: initRootLayout" + e.getMessage());
System.exit(0);
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
The MainController class declares the two tabs, the Input tab and Account tab, for the application and an exit button for closing the program. This is the MainView. fxml file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tabpane1.view.MainController">
<children>
<TabPane fx:id="tabPane" prefHeight="345.0" prefWidth="600.0" style="-fx-background-color: blue;" tabClosingPolicy="UNAVAILABLE">
<tabs>
<Tab fx:id="inputTab" closable="false" text="Input">
<content>
<fx:include source="InputView.fxml" />
</content>
</Tab>
<Tab fx:id="detailTab" closable="false" text="Detail">
<content>
<fx:include source="DetailView.fxml" />
</content>
</Tab>
</tabs>
</TabPane>
<Button fx:id="exitBtn" layoutX="529.0" layoutY="355.0" mnemonicParsing="false" onAction="#handleExitBtn" text="Exit" />
</children>
</AnchorPane>
This is the java controller class for the main view contained in MainController.java:
package tabpane1.view;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
public class MainController implements Initializable {
#FXML public TabPane tabPane;
#FXML public Tab inputTab;
#FXML public Tab accountTab;
#FXML private Button exitBtn;
public DetailController detailController;
public InputController inputController;
#Override
public void initialize(URL location, ResourceBundle resources) {
detailController = new FXMLLoader(getClass().getResource("DetailView.fxml")).getController();
// System.out.println(detailController.getClass());
inputController = new FXMLLoader(getClass().getResource("InputView.fxml")).getController();
// System.out.println(inputController.getClass());
}
#FXML private void handleExitBtn() {
System.exit(0);
}
}
The two println statements are simply trying to get the references to the two tabs, which are detailController and inputController, to do something. However, when these are uncommented and run, the following dump is output:
MainApp: IOException in method: initRootLayout
SEVERE: null
file:/G:/J2EE/TabPane_1/dist/run1314937364/TabPane_1.jar!/tabpane1/view/MainView.fxml
javafx.fxml.LoadException:
file:/G:/J2EE/TabPane_1/dist/run1314937364/TabPane_1.jar!/tabpane1/view/MainView.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at tabpane1.MainApp.initRootLayout(MainApp.java:43)
at tabpane1.MainApp.start(MainApp.java:33)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at tabpane1.view.MainController.initialize(MainController.java:24)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 13 more
When the printlns are commented out, the outcome is as expected, that is the tab pane is correctly displayed:
As mentioned the detail and input controllers are empty, but for completeness they are as follows:
InputView.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tabpane1.view.InputController">
</AnchorPane>
The controller InputController.java:
package tabpane1.view;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
public class InputController implements Initializable {
#Override
public void initialize(URL location, ResourceBundle resources) {}
}
DetailView.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: transparent;" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="tabpane1.view.DetailController" />
The controller DetailController.java:
package tabpane1.view;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
public class InputController implements Initializable {
#Override
public void initialize(URL location, ResourceBundle resources) {}
}

The way to get reference to the controller of an embedded FXML is described in this article.
You simply have to give an fx:id to the included resource:
<fx:include fx:id="IncludedView" source="InputView.fxml" />
Get a reference to IncludedView in the MainController:
#FXML private Parent IncludedView;
Get a reference to its controller simply by appending the word Controller in addition to the variable name of the embedded element:
#FXML private InputController IncludedViewController;
That is all.
Test it with:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
public class MainController implements Initializable {
#FXML private Parent IncludedView;
#FXML private InputController IncludedViewController; // $IncludedView;+Controller
#Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println(IncludedView.getClass());
System.out.println(IncludedViewController.getClass() );
}
#FXML private void handleExitBtn() {
System.exit(0);
}
}
An MRE for the sake of future readers:
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class GetEmbeddedController extends Application {
#Override
public void start(Stage primaryStage) {
try {
Pane root = (Pane) FXMLLoader.load(getClass().getResource("MainView.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(null);
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<children>
<fx:include fx:id="includedView" source="IncludedView.fxml" />
<Button layoutX="401.0" layoutY="354.0" onAction="#handleTestBtn" text="Test Included Controller" />
</children>
</AnchorPane>
MainController.java
import javafx.fxml.FXML;
import javafx.scene.Parent;
public class MainController{
#FXML private Parent includedView; //not used in this demo
/*
* Get a reference to IncludedView controller simply by appending
* the word Controller in addition to the variable name of the embedded
* element:$IncludedView;+Controller
*/
#FXML private IncludedViewController includedViewController;
#FXML private void handleTestBtn() {
includedViewController.showAlert();
}
}
IncludedView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Text?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="IncludedViewController">
<children>
<Text layoutX="277.0" layoutY="196.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Included Fxml" />
</children>
</AnchorPane>
IncludedViewController.java
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class IncludedViewController{
void showAlert(){
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Alert invoked by IncludedViewController ");
alert.show();
}
}

Related

How can I alter GUI elements of a stages owner?

I'm currently trying to figure out how to implement a feature in which the user clicks a button and a popup appears, and then the user enters data into that popup, clicks a confirm button, and the data becomes visible in the popups owner. I was able to make data from the owner stage carry over to the popup stage after follow Bro Code's tutorial on making controllers communicate, however getting it to work the other way around is proving troublesome. Below is a project in which I've isolated the issue to try and figure it out.
App.java
package org.example;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.Objects;
public class App extends Application {
public static Stage stage;
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("primary.fxml")));
Scene scene = new Scene(root);
stage = new Stage();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
PrimaryController.java
package org.example;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class PrimaryController {
#FXML
Label label;
#SuppressWarnings("unused")
public void login(ActionEvent event) throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("secondary.fxml"));
Parent root = loader.load();
SecondaryController secondaryController = loader.getController();
secondaryController.stage = new Stage();
secondaryController.stage.initModality(Modality.APPLICATION_MODAL);
secondaryController.stage.initOwner(App.stage);
Scene scene = new Scene(root);
secondaryController.stage.setScene(scene);
secondaryController.stage.show();
}
public void displayMessage(String message){
label.setText(message);
}
}
SecondaryController.java
package org.example;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.io.IOException;
public class SecondaryController {
#FXML
TextField textField;
public Stage stage;
#SuppressWarnings("unused")
public void writeToOwner(ActionEvent event) throws IOException {
String message = textField.getText();
FXMLLoader loader = new FXMLLoader(getClass().getResource("primary.fxml"));
Parent root = loader.load();
PrimaryController primaryController = loader.getController();
primaryController.displayMessage(message);
stage.close();
}
}
primary.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.example.PrimaryController">
<children>
<Button layoutX="270.0" layoutY="230.0" mnemonicParsing="false" onAction="#login" text="Login" />
<Label fx:id="label" layoutX="280.0" layoutY="191.0" />
</children>
</AnchorPane>
secondary.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.example.SecondaryController">
<children>
<TextField fx:id="textField" layoutX="219.0" layoutY="187.0" onAction="#writeToOwner" />
</children>
</AnchorPane>
The current behavior that I get from this code is almost what I want, except when the user would submit the text, it closes the popup but doesn't change the popups owner.
In your SecondaryController, it looks like you're creating a second instance of PrimaryController, leaving the first unchanged when invoking writeToOwner().
One approach is to arrange for the controllers to see a common model, much as they share a common stage in your example. The simplest such model is a single ObservableValue, illustrated here. To see the effect,
Add a StringProperty named text to your SecondaryController and make it accessible. In writeToOwner(), simply update the text and the bound label will follow.
public class SecondaryController {
#FXML
TextField textField;
public Stage stage;
private final StringProperty text = new SimpleStringProperty();
public StringProperty textProperty() {
return text;
}
#SuppressWarnings("unused")
public void writeToOwner(ActionEvent event) throws IOException {
text.set(textField.getText());
stage.close();
}
}
In your PrimaryController, bind the label's textProperty() to the textProperty() of the SecondaryController.
public class PrimaryController {
#FXML
Label label;
public StringProperty text = new SimpleStringProperty();
#SuppressWarnings("unused")
public void login(ActionEvent event) throws IOException {
…
secondaryController.stage.initOwner(App.stage);
label.textProperty().bind(secondaryController.textProperty());
…
}
}
In practice, you'll want to avoid public access to class members.

JavaFX error "null pointer Exception" when passing parameter from one Controller to another Controller

i have tried all solution in youtube and google but none of them work. The problem is when i want to switch to new scene along sending data to another scene i got error saying
Null pointer Exception
public class FirstController implements Initializable {
#FXML private TextField textField;
#FXML private Button btn;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public void onClick(ActionEvent event){
//switching to new scene
FXMLLoader loader=new FXMLLoader();
loader.setLocation(getClass().getResource("/application/Second.fxml"));
try{
loader.load();
}catch(Exception e){ }
SecondController sn=loader.getController();
sn.setText(textField.getText());
Parent p=loader.getRoot();
Stage window=new Stage();
window.setScene(new Scene(p));
window.setTitle("dfd");
window.show();
}
}
main.fxml:
<AnchorPane prefHeight="450.0" prefWidth="650.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Main">
<children>
<Button fx:id="btn" layoutX="285.0" layoutY="264.0" mnemonicParsing="false" onAction="#onClick" text="Button" />
<TextField fx:id="textField" layoutX="237.0" layoutY="213.0" />
</children>
</AnchorPane>
Second controller :
public class SecondController implements Initializable {
#FXML private Label labelField;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public void setText(String name){
this.labelField.setText(name);
}
}
Second.fxml:
`<AnchorPane prefHeight="450.0" prefWidth="650.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label fx:id="labelField" layoutX="297.0" layoutY="208.0" text="Label" />
</children>
</AnchorPane>
Your second FXML file is missing the fx:controller attribute. Therefore, when you load it, there is no controller, and so loader.getController() returns null.
Consequently, when you call sn.setText(...), you get a null pointer exception.
Just add the missing fx:controller attribute to the second FXML file. Assuming that SecondController is in the application package, this will look like:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.Label?>
<AnchorPane prefHeight="450.0" prefWidth="650.0" fx:controller="application.SecondController" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label fx:id="labelField" layoutX="297.0" layoutY="208.0" text="Label" />
</children>
</AnchorPane>
Also note that it's very bad practice to silently "squash" exceptions, by using
try {
/* ... */
} catch (Exception e) { }
It's especially bad if the ensuing code depends on the code in the try block succeeding. In particular, in this case if your call to load() results in an exception (which may happen for a multitude of reasons, including the FXML not being found or being invalid, the fx:id and field names, or types,
not matching, method names for handlers not matching or having the wrong parameters, etc.), then the load method will silently fail and the controller will not be set in the loader. This will again result in sn being null.
Here's a complete example using your code, but with the other errors fixed as well as the missing fx:controller attribute inserted:
application/Main.java:
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(FXMLLoader.load(getClass().getResource("First.fxml")));
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
application/First.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<AnchorPane prefHeight="450.0" prefWidth="650.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.FirstController">
<children>
<Button fx:id="btn" layoutX="285.0" layoutY="264.0" mnemonicParsing="false" onAction="#onClick" text="Button" />
<TextField fx:id="textField" layoutX="237.0" layoutY="213.0" />
</children>
</AnchorPane>
application/FirstController.java:
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class FirstController implements Initializable {
#FXML private TextField textField;
#FXML private Button btn;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public void onClick(ActionEvent event) throws Exception {
//switching to new scene
FXMLLoader loader=new FXMLLoader();
loader.setLocation(getClass().getResource("/application/Second.fxml"));
loader.load();
SecondController sn=loader.getController();
sn.setText(textField.getText());
Parent p=loader.getRoot();
Stage window=new Stage();
window.setScene(new Scene(p));
window.setTitle("dfd");
window.show();
}
}
application/Second.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.Label?>
<AnchorPane prefHeight="450.0" prefWidth="650.0" fx:controller="application.SecondController" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label fx:id="labelField" layoutX="297.0" layoutY="208.0" text="Label" />
</children>
</AnchorPane>
application/SecondController.java
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class SecondController implements Initializable {
#FXML private Label labelField;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public void setText(String name){
this.labelField.setText(name);
}
}

Is there a way to select a text field in code without clicking on it (javafx)?

I am not sure how to or even if it is possible to select text fields in code. I could not find anything on the subject. If the is indeed a way to do so i have a template that could be modified to demonstrate how this could be done.
Here is the template/sample code:
Main class:
package application;
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 void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
Scene scene = new Scene(root,600,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("Test");
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainControl class:
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class MainControl implements Initializable {
#FXML
Button button;
#FXML
TextField field1;
#FXML
TextField field2;
boolean field1selected=true;
public void initialize(URL arg0, ResourceBundle arg1) {
}
public void switchTextFeild(ActionEvent event){
/*
The code for switch on witch TextField is selected would go here
*/
}
}
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainControl">
<children>
<TextField fx:id="field1" layoutX="6.0" layoutY="2.0" prefHeight="394.0" prefWidth="149.0" />
<TextField fx:id="field2" layoutX="445.0" layoutY="2.0" prefHeight="394.0" prefWidth="149.0" />
<Button fx:id="button" layoutX="177.0" layoutY="14.0" mnemonicParsing="false" onAction="#switchTextFeild" prefHeight="95.0" prefWidth="239.0" text="Switch" textAlignment="CENTER" wrapText="true">
<font>
<Font size="24.0" />
</font>
</Button>
</children>
</AnchorPane>
You can use
field1.requestFocus();
in your initialize() method, so your TextField field1 will be focused after your app is started.
But notice, you have to wrap the requestFocus() call within a
Platform.runLater(new Runnable() {
#Override
public void run() {
field1.requestFocus();
}
});
because this should be done on the JavaFX Application Thread and not on the Launcher Thread, so if you would only call field1.requestFocus() this wont have any effect on our TextField.
This is very simple
filedname.requestFocus();
fieldname.selectAll();
you have to first get the focus then use selectAll()function . if you will not use requestFocus() function then selectAll() will not work
The solution is simple for classic java. You can use code below for select text in a textField without doubleclicking on it (no idea about javafx).
field1.requestFocus();
field1.setSelectionStart(0);
field1.setSelectionEnd(field1.getText().length());

JAVA FXML create a tree with custom check boxes

I am trying to create a tree with custom check boxes. There is no option in the Scenebuilder with such an option. I tried to write the code in the controller, but did not work.
Someone please help me out.
FXML and the controller code:
the CheckBoxTreeItem is not working.
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="486.9609375" prefWidth="472.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="abcd.controller">
<!-- TODO Add Nodes -->
<children>
<Button id="button" fx:id="button1" layoutX="99.0" layoutY="51.0" mnemonicParsing="false" onAction="#processLogin" text="Button" />
<TextArea fx:id="textarea" layoutX="40.0" layoutY="83.0" prefHeight="76.0" prefWidth="129.0" wrapText="true" />
<TreeView fx:id="treeview" layoutX="69.0" layoutY="204.0" prefHeight="200.0" prefWidth="200.0" />
</children>
</AnchorPane>
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.CheckBoxTreeItemBuilder;
import javafx.scene.control.TextArea;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.util.Callback;
public class controller implements Initializable {
// Binding with the FXML
#FXML
private Button taskBarButton1;
#FXML private TextArea textarea;
#FXML private TreeView<String> treeview;
#FXML private CheckBoxTreeItem<String> root;
//#FXML private CheckBoxTreeItem<String> rootitem ;
#FXML
private void processLogin(ActionEvent event) {
textarea.appendText("clicked");
}
public void loadonstart()
{
for (int i=0; i<5;i++)
{
//System.out.println("numbers" +i);
textarea.appendText("\n"+i);
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
loadonstart();
loadtreeitems();
}
private void loadtreeitems()
{
CheckBoxTreeItem<String> root = new CheckBoxTreeItem<String>("Source Root");
root.setExpanded(true);
TreeView<String> tree = new TreeView<String> (root);
//tree.setCellFactory(CheckBoxTreeCell.<String>forTreeView());
for (int j=10; j<15; j++)
{
root.setExpanded(true);
root.getChildren().add(new CheckBoxTreeItem<String>("" +j));
}
treeview.setRoot(root);
}
}

JavaFX showing view make in scene builder with controller

I have this controller:
package cz.vutbr.feec.bmds.cv2;
import java.awt.Button;
import java.awt.TextField;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Slider;
public class TestGuiController {
private int buttonPressed = 0;
#FXML
private Button tlacitko;
#FXML
private TextField textovePole;
#FXML
private Slider slider;
public void buttonPressed(ActionEvent e) {
buttonPressed++;
textovePole.setText(Integer.toString(buttonPressed));
}
}
this fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<AnchorPane prefHeight="200.0" prefWidth="200.0" xmlns:fx="http://javafx.com/fxml" fx:controller="cz.vutbr.feec.bmds.cv2.TestGuiController">
<children>
<Button fx:id="tlacitko" layoutX="30.0" layoutY="40.0" mnemonicParsing="false" onTouchPressed="#buttonPressed" text="Button" />
<Slider fx:id="slider" layoutX="157.0" layoutY="17.0" orientation="VERTICAL" />
<TextField fx:id="textovePole" layoutX="14.0" layoutY="89.0" prefWidth="134.0" />
</children>
</AnchorPane>
and this is my main class:
package cz.vutbr.feec.bmds.cv2;
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 {
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("TestGui.fxml"));
primaryStage.setTitle("Titulek");
primaryStage.setScene(new Scene(root,300,275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
When I run this through ant I get message box with error (exception during running application). I tried simple fxml without controller and it works so I am guesing I do something wrong with controller. What I must change to have it working?
I must answer my own question. Problem was in TestGuiController where I used java.awt.Button and java.awt.TextField instead of javafx.scene.control.Button and javafx.scene.control.TextField.
I'm not 100% sure but try:
in FXML: Button: onAction instead of onTouchPressed
Please provide the exact Exception message.

Categories

Resources