Getting access to ui elements in different fxml file - java

I have a FXML-application with a main.fxml, which includes two other fxml files. Each of these fxml files has its own controller class.
My question is, of how to get access to objects from a specific controller, although these objects are defined on another fxml file.
The following code is just a minimal example. I thought it was a good idea to split ui elements in different fxml files, because they are getting larger and larger.
My main fxml:
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<fx:include fx:id="top" source="top.fxml"/>
<fx:include fx:id="bottom" source="bottom.fxml"/>
</VBox>
top.fxml:
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="ControllerTop">
<children>
<Button fx:id="topbtn" onAction="#printOutput" text="OK" />
</children>
</VBox>
bottom.fxml
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="ControllerBottom">
<children>
<Button fx:id="bottombtn" onAction="#printOutput" text="OK" />
</children>
</VBox>
For top.fxml i have created this controller class:
public class ControllerTop {
#FXML public Button topbtn;
#FXML public Button bottombtn;
#FXML
public void printOutput() {
System.out.println("Hello from top button");
topbtn.setDisable(true); //OK!
bottombtn.setDisable(false); //Failed
}
}
Of course bottombtn is defined in bottom.fxml and has its own controller. The problem is, that bottombtn of printOut() of this ControllerTop results in a NullPointerException. So i need help by accessing objects in a nice and smart way.
Thanks

in main controller:
public class MainController {
/**
* var name has to be topController
*/
public TopController topController;
/**
* var name has to be bottomController
*/
public BottomController bottomController;
public void initialize(){
Button topbtn=topController.topbtn;
Button bottombtn=bottomController.bottombtn;
topbtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello from top button");
topbtn.setDisable(true); //OK!
bottombtn.setDisable(false); //Failed
}
});
}
}
bottom.fxml:
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="BottomController">
<children>
<Button fx:id="bottombtn" text="OK" />
</children>
</VBox>
top.fxml:
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="TopController">
<children>
<Button fx:id="topbtn" text="OK" />
</children>
</VBox>
and in class TopController and BottomController set #FXML public Button **btnName**;
BottomController:
public class BottomController {
public Button bottombtn;
}
TopController:
public class TopController {
public Button topbtn;
}
Another option it to use initialize at MainController to set the value of bottombtn in topController

Related

CustomTextField doesn't work when added in Fxml

I have TextField with cross to clear input. When I'm adding it like this:
public class Controller implements Initializable {
#FXML
private TextField autoCompleteTextField = TextFields.createClearableTextField();
...
and then:
#Override
public void initialize(URL location, ResourceBundle resources){
autoComplete1 = TextFields.bindAutoCompletion(autoCompleteTextField,callback, converter);
autoCompletePane.getChildren().add(autoCompleteTextField);
Everything works great. But when i want to add this item in SceneBuilder or manualy in Fxml:
<Pane fx:id="autoCompletePane" prefHeight="30.0" prefWidth="444.0">
<children>
<CustomTextField fx:id="autoCompleteTextField" layoutX="25.0" layoutY="3.0" />
// or TextField instead of CustomTextField
</children>
</Pane>
normal TextField is inserted, without cross to clear input.
What can i do?
You can specify a static method not taking parameters to create the textfield using the fx:factory attribute:
<Pane fx:id="autoCompletePane" prefHeight="30.0" prefWidth="444.0">
<children>
<TextFields fx:id="autoCompleteTextField" fx:factory="createClearableTextField" layoutX="25.0" layoutY="3.0" />
</children>
</Pane>
(This requires an import processing instruction for the TextFields class of course.)

How to set an additional FXML layout to an existing one

so I have two Controllers: the MainControllerand an ImageContainerboth have a FXML layout. In my MainController i set up a SplitPane and inside of it a FlowPane now I want to load the layout of the ImageContainer in the flowpane at runtime:
PROBLEM
How do I place the layout inside the flowpane with pre filled values in textFields, set an image etc.?
Idea
ImageContainer must extend Pane, and in the MainController I have to call the constructor of the ImageContainer and add the ImageContainer to the flowpane:
ImageContainer imgC = new ImageContainer(4,2,"location");
fp_contentFlowPane.getChildren().add(imgC);
Caused by: java.lang.NullPointerException
Caused by: java.lang.reflect.InvocationTargetException
If anyone has an ideas, help is appreciated!
Code snippet Part of ImageContainer Contoller:
public class ImageContainer extends Pane {
public HBox hbx_elementContainer;
public Label lb_likeCount;
public Label lb_commentCount;
public Label lb_location;
public ImageContainer(int likeCount, int commentCount, String location) {
this.lb_likeCount.setText(String.valueOf(likeCount));
this.lb_commentCount.setText(String.valueOf(commentCount));
this.lb_location.setText(location);
Image image = new Image("/sampleFoto.JPG");
iv_feedImage.setImage(image);
}
}
Code snippet Part of MainController Note this is not the whole code:
public class MainScreenController{
public TextField tf_userName;
public ListView lv_listView;
public FlowPane fp_contentFlowPane;
public SplitPane sp_splitPane;
public void onItemClicked(MouseEvent mouseEvent) throws IOException {
int index = lv_listView.getSelectionModel().getSelectedIndex();
if (mouseEvent.getButton().equals(MouseButton.SECONDARY)) {
if (index >= 0) {
lv_listView.getItems().remove(index);
userList.remove(index);
}
}
else{
//fp_contentFlowPane.getChildren().add(new
ImageContainer(5,5,"test"));
ImageContainer imgC = new ImageContainer(4,2,"location");
fp_contentFlowPane.getChildren().add(imgC);
}
}}
Code snippet Main
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
Parent root = loader.load();
primaryStage.setTitle("Get Viral");
primaryStage.setScene(new Scene(root, 1000, 700));
primaryStage.show();
primaryStage.getIcons().add(new Image("/iconSpectures.jpg"));
}
public static void main(String[] args) {
launch(args);
}
}
FXML of ImageContainer:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.text.Font?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="200.0" prefWidth="200.0"
xmlns="http://javafx.com/javafx/8.0.172-ea"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.ImageContainer">
<bottom>
<HBox fx:id="hbx_elementContainer" prefHeight="31.0" prefWidth="600.0"
BorderPane.alignment="CENTER">
<children>
<Label fx:id="lb_likeCount" contentDisplay="TOP" text="Label">
<HBox.margin>
<Insets right="10.0" />
</HBox.margin></Label>
<Label fx:id="lb_commentCount" text="Label">
<HBox.margin>
<Insets right="20.0" />
</HBox.margin></Label>
<Label fx:id="lb_location" text="Label" />
<Label fx:id="lb_accountHolder" text="Label" />
<Button mnemonicParsing="false" text="Download">
<font>
<Font name="Arial Bold" size="11.0" />
</font>
<HBox.margin>
<Insets right="10.0" />
</HBox.margin>
</Button>
</children>
</HBox>
</bottom>
<center>
<AnchorPane prefHeight="200.0" prefWidth="200.0"
BorderPane.alignment="CENTER">
<children>
<ImageView fx:id="iv_feedImage" fitHeight="150.0"
fitWidth="200.0"
pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="0.0"
AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
</center>
</BorderPane>
If you want your ImageContainer to make use of your FXML then you can simply load it in the constructor using FXMLLoader and get rid of the fx:controller="sample.ImageContainer" from your FXML.
Here's a post about when to use which method of setting a controller for an fxml file to use (fx:controller vs FXMLLoader); Because your ImageContainer constructor requires arguments, it's easier imo to use the FXMLLoader method.
public class ImageContainer extends Pane {
private static final PATH_FXML = "/internal/path/to/layout.fxml"
#FXML public HBox hbx_elementContainer;
#FXML public Label lb_likeCount;
#FXML public Label lb_commentCount;
#FXML public Label lb_location;
public ImageContainer(int likeCount, int commentCount, String location) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_FXML));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.lb_likeCount.setText(String.valueOf(likeCount));
this.lb_commentCount.setText(String.valueOf(commentCount));
this.lb_location.setText(location);
Image image = new Image("/sampleFoto.JPG");
iv_feedImage.setImage(image);
}
}
For some extra fun stuff: If you define getters and setters on a custom Control, then you can use them in the attributes of that control in FXML.
It's not exactly necessary for your use case, but you can do stuff like this.
Custom Control:
package path.to.my_package;
public class MyControl extends Control {
private String myField;
public String getMyField() { return myField; }
public void setMyField(String myField) { this.myField = myField; }
}
FXML:
<?import path.to.my_package.MyControl ?>
<BorderPane xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1">
<center>
<MyControl myField="myValue"/>
</center>
</BorderPane>

Share model with nested controller

I'm trying to build a simple GUI with JavaFX using SceneBuilder, where I'm using a MenuItem (in Main.fxml) to select a root folder. The folder's contents are then listed in a TextArea that again is wrapped in a TabPane (FileListTab.fxml, nested FXML that is included in Main.fxml).
I used this post as a starting point to get used to MVC. Unfortunately I don't know how to make my nested FXML listen or be bound to the outer one since I'm not explicitly calling it. Right now I'm stuck just to display my chosen folder in a label.
My minimal working code right now looks like this:
Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" onAction="#browseInputFolder" text="Open folder" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
<center>
<TabPane prefHeight="200.0" prefWidth="200.0" tabClosingPolicy="UNAVAILABLE" BorderPane.alignment="CENTER">
<tabs>
<Tab text="File listing">
<content>
<fx:include fx:id="analysisTab" source="FileListTab.fxml" />
</content>
</Tab>
</tabs>
</TabPane>
</center>
</BorderPane>
FileListTab.fxml
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" spacing="15.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="FileListController">
<children>
<HBox spacing="10.0">
<children>
<Label minWidth="100.0" text="Root folder:" />
<Label fx:id="label_rootFolder" />
</children>
</HBox>
<TextArea prefHeight="200.0" prefWidth="200.0" />
<HBox spacing="10.0">
<children>
<Label minWidth="100.0" text="Found files:" />
<Label fx:id="label_filesFound" />
</children>
</HBox>
</children>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</VBox>
Model.java (the supposed to be shared model between controllers)
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Model {
private StringProperty rootFolder;
public String getRootFolder() {
return rootFolderProperty().get();
}
public StringProperty rootFolderProperty() {
if (rootFolder == null)
rootFolder = new SimpleStringProperty();
return rootFolder;
}
public void setRootFolder(String rootFolder) {
this.rootFolderProperty().set(rootFolder);
}
}
NestedGUI.java (Main class)
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.IOException;
public class NestedGUI extends Application {
Model model = new Model();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Parent root = null;
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getClassLoader().getResource("Main.fxml"));
root = (BorderPane) fxmlLoader.load();
MainController controller = fxmlLoader.getController();
controller.setModel(model);
// This openes another window with the tab's content that is actually displaying the selected root folder
/* FXMLLoader fxmlLoader2 = new FXMLLoader();
fxmlLoader2.setLocation(getClass().getClassLoader().getResource("FileListTab.fxml"));
VBox vBox = (VBox) fxmlLoader2.load();
FileListController listController = fxmlLoader2.getController();
listController.setModel(model);
Scene scene = new Scene(vBox);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();*/
} catch (IOException e) {
e.printStackTrace();
}
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
MainController.java
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import java.io.File;
public class MainController {
Model model;
public void setModel(Model model) {
this.model = model;
}
public void browseInputFolder() {
DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle("Select folder");
File folder = chooser.showDialog(new Stage());
if (folder == null)
return;
String inputFolderPath = folder.getAbsolutePath() + File.separator;
model.setRootFolder(inputFolderPath);
System.out.print(inputFolderPath);
}
}
FileListController.java
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class FileListController {
Model model;
#FXML
Label label_rootFolder;
public void setModel(Model model) {
label_rootFolder.textProperty().unbind();
this.model = model;
label_rootFolder.textProperty().bind(model.rootFolderProperty());
}
}
I looked through various posts here on SO, but either I didn't understand the answers or others had different problems.
Can somebody give me some pointers? (hints to solve this, code snippets, links...) It looks like a pretty basic FXML-problem, but I just don't get it.
Simple solution
One option is just to inject the "nested controller" into the main controller as described in the FXML documentation.
The rule is that the field name for the controller should be the fx:id for the <fx:include> with the string "Controller" appended. So in your case, fx:id="analysisTab" and so the field will be FileListController analysisTabController. Once you have done that, you can pass the model to the nested controller when it is set in the main controller:
public class MainController {
Model model;
#FXML
private FileListController analysisTabController ;
public void setModel(Model model) {
this.model = model;
analysisTabController.setModel(model);
}
// ...
}
Advanced solution
One drawback to the simple solution above is that you have to propagate the model manually to all nested controllers, which can become tricky to maintain (especially if you have multiple levels of <fx:include>s). Another drawback is that you are setting the model after the controller is created and initialized (so, for example, the model is not available in the initialize() method, which is where you would most naturally like to use it).
A more advanced approach is to set a controllerFactory on the FXMLLoader. The controllerFactory is a function that maps the controller class (specified by the fx:controller attribute in the fxml file) to an object (almost always an instance of that class) that will be used as the controller. The default controller factory just invokes the no-argument constructor on the class. You can use this to invoke a constructor taking the model, so the model is available as soon as the controller is instantiated.
If you set a controller factory, the same controller factory is used for any included fxml files.
So you could rewrite your controllers to have constructors taking a model instance:
public class MainController {
private final Model model;
public MainController(Model model) {
this.model = model;
}
public void browseInputFolder() {
DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle("Select folder");
File folder = chooser.showDialog(new Stage());
if (folder == null)
return;
String inputFolderPath = folder.getAbsolutePath() + File.separator;
model.setRootFolder(inputFolderPath);
System.out.print(inputFolderPath);
}
}
and in the FileListController this means you can now access the model directly in the initialize() method:
public class FileListController {
private final Model model;
#FXML
Label label_rootFolder;
public FileListController(Model model) {
this.model = model ;
}
public void initialize() {
label_rootFolder.textProperty().bind(model.rootFolderProperty());
}
}
Now your application class needs to create a controller factory that invokes these constructors. This is the tricky part: you probably want to use some reflection here and implement logic of the form: "if the controller class has a constructor taking a model, invoke it with the (shared) model instance; otherwise invoke the default constructor". This looks like:
public class NestedGUI extends Application {
Model model = new Model();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Parent root = null;
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getClassLoader().getResource("Main.fxml"));
fxmlLoader.setControllerFactory((Class<?> type) -> {
try {
for (Constructor<?> c : type.getConstructors()) {
if (c.getParameterCount() == 1 && c.getParameterTypes()[0] == Model.class) {
return c.newInstance(model);
}
}
// default behavior: invoke no-arg constructor:
return type.newInstance();
} catch (Exception exc) {
throw new RuntimeException(exc);
}
});
root = (BorderPane) fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
At this point you are basically one step along the way to creating a dependency injection framework (you are injecting the model into the controllers using a factory class...)! So you might just consider using one instead of creating one from scratch. afterburner.fx is a popular dependency-injection framework for JavaFX, and the core of the implementation is essentially the ideas in the code above.
An option I prefer is to use a custom component, instead of the <fx:include fx:id="analysisTab" source="FileListTab.fxml" />. So in Main.fxml, replace the <fx:include> line with:
<FileList fx:id="fileList"></FileList>
FileList is our new, custom component. You must also add <?import yourpackage.*?> to the top of Main.fxml, to make the classes of yourpackage available to FXML. (Obviously, yourpackage is the package containing all the classes and files in this question.)
Add below is the class for the custom component in yourpackage.FileList.java; mostly your code from the FileListController + the code required to load the FXML. Note however that it extends a JavaFX component, the VBox, making it a FXML component itself. The VBox was the root component in your FileListTab.fxml and must also be declared in the type attribute of the FileList.fxml below.
package yourpackage;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
public class FileList extends VBox {
private Model model; // NOT REALLY NEEDED! KEEPING IT BECAUSE YOUR FileListController HAD IT TOO...
#FXML
Label label_rootFolder;
public FileList() {
java.net.URL url = getClass().getResource("/yourpackage/FileList.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(url);
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
}
catch( IOException e ) {
throw new RuntimeException(e);
}
}
public void setModel(Model model) {
label_rootFolder.textProperty().unbind();
this.model = model; // NOT REALLY NEEDED!
label_rootFolder.textProperty().bind(model.rootFolderProperty());
}
}
And the FileList.fxml. This is your own FileListTab.fxml, having its root VBox node replaced by the fx:root and the type="javafx.scene.layout.VBox" attribute, keeping all other attributes the same:
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<fx:root xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2"
type="javafx.scene.layout.VBox"
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" spacing="15.0"
>
<children>
<HBox spacing="10.0">
<children>
<Label minWidth="100.0" text="Root folder:" />
<Label fx:id="label_rootFolder" />
</children>
</HBox>
<TextArea prefHeight="200.0" prefWidth="200.0" />
<HBox spacing="10.0">
<children>
<Label minWidth="100.0" text="Found files:" />
<Label fx:id="label_filesFound" />
</children>
</HBox>
</children>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</fx:root>
Did you notice the fx:id in the <FileList> component above? You can now inject it in the MainController:
#FXML
private FileList fileList;
And propagate the setModel() call:
// in MainController
public void setModel(Model model) {
this.model = model;
this.fileList.setModel(model);
}

JavaFx custom components with Spring

I'm currently trying to create custom components in JavaFx for my desktop app, and I would like to use Spring DI.
I have read about how to make extendable components and without Spring I can do it, based on this code https://github.com/matrak/javafx-extend-fxml.
But when I replace the FXMLLoader with a custom SpringFXMLLoader it can't load the components.
In the main window, there is a button and a editbox, and on click I woul'd like to create a new custom module, with the given name. But it says, that the label in the custom component is null.
What am I doing wrong?
BasicModule.class
#org.springframework.stereotype.Controller
#DefaultProperty(value = "extension")
public class BasicModule extends BorderPane {
public Label label;
public AnchorPane extension;
public BasicModule() {
super();
}
public ObservableList<Node> getExtension() {
return extension.getChildren();
}
}
BasicModule.fxml
<fx:root type="javafx.scene.layout.BorderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"
prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.akos.fxmlTest.BasicModule">
<top>
<Label fx:id="label" text="Label Basic" BorderPane.alignment="CENTER"/>
</top>
<center>
<AnchorPane fx:id="extension" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER"/>
</center>
</fx:root>
CustomModule.class
public class CustomModule extends BasicModule {
#FXML
public Label customModuleLabel;
public void setText(String text) {
customModuleLabel.setText(text);
}
}
CustomModule.fxml
<fx:root type="com.akos.fxmlTest.BasicModule" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.akos.fxmlTest.CustomModule">
<Label fx:id="customModuleLabel" text="asdasdasdasd"/>
</fx:root>
Main.class
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfiguration.class);
context.getBeanFactory().registerResolvableDependency(Stage.class, primaryStage);
SpringFxmlLoader loader = context.getBean(SpringFxmlLoader.class);
Parent parent = (Parent) loader.load("/fxml/main.fxml");
primaryStage.setScene(new Scene(parent, 1000, 600));
primaryStage.setTitle("test");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
main.fxml
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.akos.fxmlTest.Controller">
<center>
<VBox fx:id="itemList" prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets left="50.0" right="50.0" />
</BorderPane.margin>
</VBox>
</center>
<left>
<VBox prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
<children>
<Button fx:id="addButton" mnemonicParsing="false" onAction="#addNewModule" text="Button" />
<TextField fx:id="moduleNameEdit" />
</children>
</VBox>
</left>
</BorderPane>
Controller.class
#org.springframework.stereotype.Controller
public class Controller {
public VBox itemList;
public Button addButton;
public TextField moduleNameEdit;
public void addNewModule(ActionEvent actionEvent) {
CustomModule customModule = new CustomModule();
itemList.getChildren().add(customModule);
customModule.setText(moduleNameEdit.getText());
}
}
AppConfiguration.class
#Configuration
#ComponentScan("com.akos.fxmlTest")
public class AppConfiguration {}
Sorry for the wall of text.

How do I make my VBox and Label resize according to texts in label in JavaFx?

As you can see, my texts are constrained by labels. How do I make the label resize to exactly fit the text and also to resize the VBox and GridPane accordingly. I only want to resize vertically.
My FXML:
<VBox fx:id="body"
alignment="TOP_CENTER"
prefHeight="150"
GridPane.vgrow="SOMETIMES"
prefWidth="300"
GridPane.columnIndex="0"
GridPane.rowIndex="1" spacing="5">
<Label alignment="CENTER" textAlignment="JUSTIFY" fx:id="word" maxWidth="268"/>
<Pane prefHeight="10" VBox.vgrow="NEVER"/>
<Label alignment="CENTER" textAlignment="JUSTIFY" wrapText="true" fx:id="meaning" maxWidth="268" />
<Label alignment="CENTER" textAlignment="JUSTIFY" wrapText="true" fx:id="sentence" maxWidth="268" />
</VBox>
This VBox is inside the GridPane:
<GridPane fx:id="base"
alignment="CENTER"
prefHeight="210.0"
maxWidth="310.0"
stylesheets="#style.css"
vgap="0" xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sample.Controller">
...
Minimal, Complete, and Verifiable example as requested by #James_D
Main Class:
public class Main extends Application {
private Stage stage;
private StackPane stackPane;
#Override
public void start(Stage primaryStage) throws Exception{
stage = primaryStage;
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = (Parent) loader.load();
stackPane = new StackPane(root);
Scene scene = new Scene(stackPane);
scene.setFill(Color.WHITE);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller Class:
public class Controller implements Initializable{
#FXML private Label label1;
#FXML private Button changeLabel;
private StringProperty labelString = new SimpleStringProperty();
#Override
public void initialize(URL location, ResourceBundle resources) {
labelString.setValue("aasdasd sad asdasd asdasda");
label1.textProperty().bind(labelString);
}
#FXML
public void clicked(MouseEvent e){
labelString.setValue("asdsadasd asdasdasd sfdgsfwoef fgtrhfgbdrgdf dfgdfivbjkfd gdfgidfjvdf gdfgjldkvbdf gjdilgjdfv dfgojdflkgdf ");
}
}
sample.fxml:
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10" maxHeight="Infinity">
<children>
<VBox fx:id="body"
alignment="CENTER"
maxHeight="Infinity"
GridPane.vgrow="SOMETIMES"
prefWidth="300"
GridPane.columnIndex="0"
GridPane.rowIndex="1" spacing="5">
<Label alignment="CENTER" VBox.vgrow="ALWAYS" wrapText="true" textAlignment="CENTER" fx:id="label1" maxWidth="268"/>
<Button fx:id="changeLabel" text="Change" minWidth="50" onMouseClicked="#clicked" maxWidth="Infinity" />
</VBox>
</children>
Expectation:
When I press 'Change' button, Everything should resize to just give enough space for text to be shown.
Problem:
When I press 'Change' button, UI remains same not showing the full text.
Assuming you want the text to wrap, the labels will need to be able to grow vertically. Add the attribute
maxHeight="Infinity"
to each label. You are also constraining the overall height of the VBox with prefHeight="150"; remove that attribute and let the VBox figure out its own height. Similarly, you probably want to remove the prefHeight attribute from the GridPane.

Categories

Resources