How to create an FXML handler that accepts parameters? - java

I am developing a small, fake, Mail Client in JavaFXML.
It offers a Listview with messages written on a txt file, a TextArea which prints selected message and some buttons.
Here's an Image of the Main View: https://ibb.co/iKN2rm
I already took care of "New Message" Button, which is launching a new FXML View and works well.
Here's an Image of the "New_Message" View: https://ibb.co/hQf5Bm
Now I'm trying to implement the "Reply" button, which should launch the same View as before (New Message) but set on all three TextFields strings taken from the Main View, such as Message's text, recipient and Message Argument.
Below the New Message Button Handler:
private void handle_new(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Client/Resources/new_utente1.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setTitle("New Message");
stage.setScene(new Scene(root1));
stage.show();
} catch (Exception ecc) {
System.out.println("ERROR: " + ecc.getMessage());
}
}
I tried to implement the handle_reply method, but I'm not able to add parameters because FXML file won't find the method if I do so.
Below a small part of the FXML file:
<TextArea fx:id = "testo" editable="false" layoutX="283.0" layoutY="53.0" prefHeight="450.0" prefWidth="490.0" promptText="Select a message and it will be displayed here..." />
<Button id="nuovo" layoutX="46.0" layoutY="521.0" onAction = "#handle_new" mnemonicParsing="false" prefHeight="25.0" prefWidth="173.0" text="New Message" />
<Button id="reply" layoutX="283.0" layoutY="521.0" onAction = "#handle_reply" mnemonicParsing="false" prefHeight="25.0" prefWidth="132.0" text="Reply" />
My question is: How do I implement the "handle_reply" method as described before?
Thank you

Create a Controller class
then connect this class to your view
private void handle_new(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Client/Resources/new_utente1.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
CController ctr = fxmlLoader.getController();
ctr.setLabelText("asdsad");
Stage stage = new Stage();
stage.setTitle("New Message");
stage.setScene(new Scene(root1));
stage.show();
} catch (Exception ecc) {
System.out.println("ERROR: " + ecc.getMessage());
}
}
and in your Controllers you'll do
public class CController implements Initializable {
#FXML TextArea testo;
#Override
public void initialize(URL location, ResourceBundle resources) {}
public void setLabelText(String text){testo.setText(text);}
}

Unfortunately it's not possible to use handlers with parameters. You should use different handler in each case.
Had this problem some time ago too. As a solution you could perform small refactoring to minimize code duplicating.
And if you know javascript you can play with this instead of using java handlers: https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html#scripting
Edit: also you can check this answer: https://stackoverflow.com/a/37902780/5572007 (pretty the same)

Related

Filling the Combobox with choices

I'm just a complete beginner when it comes to programming or java.
So for the start my plan was to create a window useing JavaFX(combined with scene builder) where I do have a button that leads me to another window where i do have a combobox. I googled for hours now to find a way to fill that combobox with choices but all the solutions i found don't work for me. Thats why I think I made some mistakes here and I hope you can somehow help me. Or at list give me a hint what I should learn/read to get to the solution myself.
So to start with, here's my main.java code where I build my first stage.
main.java:
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root= FXMLLoader.load(getClass().getResource("Scene-Hauptmenu.fxml"));
primaryStage.setTitle("Fishbase");
primaryStage.sizeToScene();
primaryStage.setResizable(false);
primaryStage.setScene(new Scene(root));
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
In my "Scene-Hauptmenu.fxml" all that matters is the button that leads me to my second window:
Scene-Hauptmenu.fxml:
<Button id="btn_gefangen" fx:id="btn_gefangen" mnemonicParsing="false" onAction="#gefangen" text="Ich habe Fische gefangen!" GridPane.rowIndex="1" />
So far everything works fine and I can switch to my second window without a problem. But I think my main problem lies within my controller class so here it is.
MyController.java:
public class MyController implements Initializable{
private Node node;
private Stage stage;
private Scene scene;
private FXMLLoader fxmlLoader;
private Parent root;
#FXML
private Button btn_gefangen;
#FXML
private ComboBox<String> chobo_fisch;
#FXML
private Button btn_gefangen_zurueck;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void gefangen(ActionEvent event) throws IOException{
node = (Node) event.getSource();
stage = (Stage) node.getScene().getWindow();
scene = stage.getScene();
fxmlLoader = new FXMLLoader (getClass().getResource("gefangen.fxml"));
root = (Parent) fxmlLoader.load();
scene.setRoot(root);
stage.sizeToScene();
stage.setTitle("Fische eintragen");
}
public void gefangen_zurueck(ActionEvent event) throws IOException{
node = (Node) event.getSource();
stage = (Stage) node.getScene().getWindow();
scene = stage.getScene();
fxmlLoader = new FXMLLoader (getClass().getResource("Scene-Hauptmenu.fxml"));
root = (Parent) fxmlLoader.load();
scene.setRoot(root);
stage.sizeToScene();
stage.setTitle("Fishbase");
}
}
So the button "btn_gefangen" leads me to that other window where i do have the combobox with the fx:id "chobo_fisch".
gefangen.fxml:
<ComboBox fx:id="chobo_Fisch" prefWidth="150.0"/>
So I googled for hours but I still didnt find any solution to fill the combobox with choices that works with my code. What did I do wrong? Can anyone help me here?
Best regards
Jannik
I found three variants, depending on your setup:
1st variant
// Weekdays
String week_days[] =
{ "Monday", "Tuesday", "Wednesday",
"Thrusday", "Friday" };
// Create a combo box
ComboBox combo_box = new ComboBox(FXCollections.observableArrayList(week_days));
(Soure: https://www.geeksforgeeks.org/javafx-combobox-with-examples/)
2nd variant
final ComboBox emailComboBox = new ComboBox();
emailComboBox.getItems().addAll(
"jacob.smith#example.com",
"isabella.johnson#example.com",
"ethan.williams#example.com",
"emma.jones#example.com",
"michael.brown#example.com"
);
Source: (https://docs.oracle.com/javafx/2/ui_controls/combo-box.htm)
3rd variant (for FXML)
<ComboBox fx:id="someName">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="1"/>
<String fx:value="2"/>
<String fx:value="3"/>
<String fx:value="4"/>
</FXCollections>
</items>
<value>
<String fx:value="1"/>
</value>
</ComboBox>
Edit
As mentioned by fabian you should make sure to include the FXML imports:
<?import javafx.collections.FXCollections?>
<?import java.lang.String?>
The second one may not be needed.
I'm new to those stuff but I think this is how it should look or at least close too if I understood what you wanted.
Example below:
ComboBox<String> stuff = new ComboBox<>();
stuff.getItems().addAll("1","2","5","10");
Note: I'm new to stackoverflow.
Try this:
ObservableList<String> items = FXCollections.observableArrayList();
items.add("a");
items.add("b");
chobo_fisch.getItems().addAll(items);
Your combobox must be filled with items (in your case String):
List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
chobo_fisch.setItems(FXCollections.observableArrayList(list));
If you use a combobox of a more complex object, you could use a cellfactory to choose the value that is displayed :
chobo_fisch.setCellFactory(obj -> new ChoboFischListCell());
chobo_fisch.setButtonCell(new ChoboFischListCell());
where ChoboFischListCell is a class that extends ListCell and where you implement which field of your object should be displayed.

FXMLLoader load time in JDK 8u92

In my JavaFX application I have to load many fxml files (200+) in the same time. I have decided to load them in background Task just like in https://stackoverflow.com/a/34878843 answear. Everything works fine (load time was acceptable) until JDK update. Newest version of JDK lengthened load time 3-4 times.
I have checked previous JDK releases and that problem appears from the JDK 8u92.
To test that issue I created new simple JavaFX FXML Application in Netbeans 8.1 and use only generated classes and fxml. Creating view from code works fine.
Application class:
public class FXMLLoaderTest extends Application {
private static Executor ex = Executors.newCachedThreadPool();
//private static Executor ex = Executors.newFixedThreadPool(400);
//private static Executor ex = Executors.newSingleThreadExecutor();
#Override
public void start(Stage stage) throws Exception {
VBox box = new VBox();
ScrollPane root = new ScrollPane(box);
Button b = new Button("GENERATE");
b.setOnAction(e -> {
IntStream.range(0, 1000).forEach(i -> {
Task<Parent> task = new Task<Parent>() {
#Override
protected Parent call() throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = null;
try {
root = loader.load();
} catch (IOException ex) {
Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
}
// StackPane root= new StackPane();
// Button click = new Button("Click");
// root.setPrefSize(300, 300);
// root.getChildren().add(click);
return root;
}
};
task.setOnSucceeded(ev -> {
final Parent parent = task.getValue();
box.getChildren().add(parent);
});
task.setOnFailed(ev -> task.getException().printStackTrace());
ex.execute(task);
});
});
box.getChildren().add(b);
Scene scene = new Scene(root, 400, 500);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLDocument.fxml
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxmlloader.FXMLDocumentController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>
FXMLDocumentController.java
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello World!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
I have tested this on several computers and result was always the same. On JDK 8u91 fxml files load fast. I have checked release note of 8u92 and I haven't found any changes in FXMLLoader class.
Has anybody encounter this issue? Mayby I am doing something wrong then please correct me.

JavaFX initialize() is not called on inner custom component

I am using javaFX and I need to put custom components to my scene. Therefore I have "main_pane.fxml" with grid pane containing my components (for example DocumentModule).
main_pane.fxml
<GridPane xmlns:fx="http://javafx.com/fxml" fx:controller="GUI.MainPane" gridLinesVisible="true" >
<padding>
<Insets bottom="0" top="0" left="0" right="0" />
</padding>
.
.
.
<DocumentModule fx:id="documentModule"
minWidth="200" minHeight="400"
GridPane.columnIndex="0" GridPane.rowIndex="1">
.
.
.
</DocumentModule>
.
.
.
Each of them is defined in separate fxml file.
document_module.fxml
<GridPane xmlns:fx="http://javafx.com/fxml" fx:controller="GUI.DocumentModule" >
<padding>
<Insets bottom="0" top="0" left="0" right="0" />
</padding>
<ToolBar fx:id="toolBar" GridPane.rowIndex = "0" GridPane.columnIndex = "0" orientation="HORIZONTAL" >
.
.
.
</ToolBar>
<ScrollPane fx:id="scrollPane" hbarPolicy="AS_NEEDED" vbarPolicy="AS_NEEDED" GridPane.rowIndex = "1" GridPane.columnIndex = "0">
<DocumentView fx:id="documentView"/>
</ScrollPane>
</GridPane>
Problem is that DocumentModule is not initialized after construction. It's constructor is called but not it's initialize(URL location, ResourceBundle resources) method. Therefore objects from fxml are not injected.
Controller code for document module
public class DocumentModule extends GridPane implements Initializable {
protected Document document;
#FXML
private DocumentView documentView;
#FXML
private ScrollPane scrollPane;
.
.
.
public DocumentModule() {
System.out.println("Document Module constructed.");
//this is called correctly
}
#Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("Document Module initialized.");
//This is not called at all.
}
}
For MainPane everything works fine but not for any of inner components.
The component tree seems to be constructed correctly, just the inner components are not initialized. Also the inner components are not dispalyed in application scene (if I load their fxml directly they work, if I use fx:include they are just displayed).
MainPane controller
public final class MainPane extends GridPane implements Initializable {
#FXML
private DocumentModule documentModule;
#FXML
private EditModule editModule;
public MainPane() {
System.out.println("Main Pane constructed.");
}
#Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("Main Pane initialized.");
}
}
Application entry class' start method
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("main_pane.fxml"));
GridPane root = fxmlLoader.load();
Scene scene = new Scene(root, 800, 600);
primaryStage.setMaximized(true);
primaryStage.setMinWidth(800);
primaryStage.setMinHeight(600);
primaryStage.setTitle("App");
primaryStage.setScene(scene);
primaryStage.show();
}
I haven't find any topic/page/blog with same problem. Few of them had similar symptoms, but no of solutins helped me. Does anyone have idea why initialize is not called on inner components?
Thanks!
Tom
Nowhere in your code do you actually load document_module.fxml, so the elements defined there will never be created. The initialize() method is called on the controller for an fxml file when the FXMLLoader loads that file, but since you never load the fxml file, the initialize() method is never called.
The element <DocumentModule> in your main FXML merely causes the DocumentModule class to be instantiated (via a call to its no-arg constructor), but there is no link from there to the fxml file.
It looks like you are trying to follow the FXML custom component pattern. To do so, you need to load the FXML file in the custom component constructor. Specify a dynamic root and do not specify the controller class in the fxml, and set both on the FXMLLoader before you call load:
document_module.fxml:
<fx:root type="GridPane" xmlns:fx="http://javafx.com/fxml">
<padding>
<Insets bottom="0" top="0" left="0" right="0" />
</padding>
<ToolBar fx:id="toolBar" GridPane.rowIndex = "0" GridPane.columnIndex = "0" orientation="HORIZONTAL" >
.
.
.
</ToolBar>
<ScrollPane fx:id="scrollPane" hbarPolicy="AS_NEEDED" vbarPolicy="AS_NEEDED" GridPane.rowIndex = "1" GridPane.columnIndex = "0">
<DocumentView fx:id="documentView"/>
</ScrollPane>
</fx:root>
DocumentModule.java:
public class DocumentModule extends GridPane implements Initializable {
protected Document document;
#FXML
private DocumentView documentView;
#FXML
private ScrollPane scrollPane;
.
.
.
public DocumentModule() {
System.out.println("Document Module constructed.");
FXMLLoader loader = new FXMLLoader(getClass().getResource("document_module.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
} catch (IOException exc) {
exc.printStackTrace();
// this is pretty much fatal, so:
System.exit(1);
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("Document Module initialized.");
// This will now be called after the #FXML-annotated fields are initialized.
}
}

how do I get an element in JavaFx using an id?

I am new to FXML and I am trying to create a handler for all of the button clicks using a switch. However, in order to do so, I need to get the elements using and id. I have tried the following but for some reason (maybe because I am doing it in the controller class and not on the main) I get a stack overflow exception.
public class ViewController {
public Button exitBtn;
public ViewController() throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("mainWindow.fxml"));
Scene scene = new Scene(root);
exitBtn = (Button) scene.lookup("#exitBtn");
}
}
So how will I get an element (for example a button) using it's id as a reference?
The fxml block for the button is:
<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false"
onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1"/>
Use a controller class, so that you don't need to use a lookup. The FXMLLoader will inject the fields into the controller for you. The injection is guaranteed to happen before the initialize() method (if you have one) is called
public class ViewController {
#FXML
private Button exitBtn ;
#FXML
private Button openBtn ;
public void initialize() {
// initialization here, if needed...
}
#FXML
private void handleButtonClick(ActionEvent event) {
// I really don't recommend using a single handler like this,
// but it will work
if (event.getSource() == exitBtn) {
exitBtn.getScene().getWindow().hide();
} else if (event.getSource() == openBtn) {
// do open action...
}
// etc...
}
}
Specify the controller class in the root element of your FXML:
<!-- imports etc... -->
<SomePane xmlns="..." fx:controller="my.package.ViewController">
<!-- ... -->
<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />
<Button fx:id="openBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Open" HBox.hgrow="NEVER" HBox.margin="$x1" />
</SomePane>
Finally, load the FXML from a class other than your controller class (maybe, but not necessarily, your Application class) with
Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);
// etc...

javafx set parent borderpane to null

i have 2 fxml
FXML A:
it contains borderpane with ID fx:id="UnitBorderPane"
FXML B:
it contains anchorpane with ID fx:id="UnitForm"
i load the "FXML B" at borderpane A on the left side
FXMLLoader loader = new
FXMLLoader(getClass().getResource("/projectname/unit/UnitForm.fxml"));
Pane pane = (Pane) loader.load();
UnitBorderPane.setLeft(pane);
it is kind of fxml form, so we have a button with action
<Button layoutX="102.0" layoutY="169.0" mnemonicParsing="false" onAction="#saveUnit" text="Save" />
how to hide that FXML A BorderPane left?
#FXML
private void saveUnit(ActionEvent event) {
BorderPane borpane = (BorderPane)UnitForm.getParent().lookup("#UnitBorderPane");
borpane.setLeft(null);
}
this code not work, the borpane variable is null so i cannot set the borderPane FXML A Left to null.
I think it should just be
BorderPane borpane = (BorderPane)UnitForm.getParent();
However, none of this feels very robust; for example if you decide to change the layout structure at all you will likely have a lot of code to change in various classes. I would add a property to the controller for UnitForm.fxml that you can observe from the controller for UnitBorderPane. Something like:
public class UnitFormController { // your actual class name may differ....
private final BooleanProperty saved = new SimpleBooleanProperty();
public BooleanProperty savedProperty() {
return saved ;
}
public final boolean isSaved() {
return savedProperty().get();
}
public final void setSaved(boolean saved) {
savedProperty().set(saved);
}
// other code as you already have...
#FXML
private void saveUnit() {
setSaved(true);
}
// ...
}
Then you do
FXMLLoader loader =
new FXMLLoader(getClass().getResource("/projectname/unit/UnitForm.fxml"));
Pane pane = (Pane) loader.load();
UnitFormController controller = loader.getController();
controller.savedProperty().addListener((obs, wasSaved, isNowSaved) -> {
if (isNowSaved) {
UnitBorderPane.setLeft(null);
}
});
UnitBorderPane.setLeft(pane);
Now the management of the UnitBorderPane is all in one place, instead of being split over two controllers, and there are no lookups (which are not robust). The controller for the UnitForm just sets a property and lets the other controller respond as it sees fit.

Categories