Can't pass attribute betwewen scenes JAvaFX - java

I'm trying to pass a String between scenes in JavaFX, I already followed the some answers but it seems that they don't work because the string is null in the new scene.
Here's my MainControler:
public class FXMLDocumentController implements Initializable {
#FXML
private Button btn_signup;
#FXML
private TextField et_username;
#FXML
private PasswordField et_password;
#FXML
private Hyperlink link_login;
Stage prevStage;
public void setPrevStage(Stage stage){
this.prevStage = stage;
}
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {
if(btn_signup == event.getSource()){
Conector conn = new Conector();
if (conn.checkUser(et_username.getText(), et_password.getText())) {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource("FXMLTasker.fxml"));
Pane myPane = (Pane)myLoader.load();
Scene scene = new Scene(myPane);
Stage stage = new Stage();
stage.setResizable(false);
stage.setScene(scene);
FXMLTaskerController controler = new FXMLTaskerController();
controler.setUser(et_username.getText());
myLoader.setController(controler);
prevStage.close();
stage.show();
}else {
JOptionPane.showMessageDialog(null, "Usuario o ContraseƱa incorrecta");
}
}else if (link_login == event.getSource()){
System.out.println("Registrate!");
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
Here's the other class controler, the one where i want my String.
public class FXMLTaskerController implements Initializable {
#FXML private ListView list_todo;
#FXML private ListView list_done;
#FXML public String username;
private void handleButtonAction(ActionEvent event) {
}
#Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println(username);
list_todo.setCellFactory(new TaskCellFactory());
list_done.setCellFactory(new TaskCellFactory());
try {
getTasks();
} catch (IOException ex) {
Logger.getLogger(FXMLTaskerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void setUser(String username){
this.username = username;
}
public void getTasks() throws IOException{
Conector con = new Conector();
for(Task task: con.obtenerTareas("pepin")){
System.out.println(task);
if(task.isState()){
list_done.getItems().add(task);
}else{
list_todo.getItems().add(task);
}
}
}
}
And here are the fxml files:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Hyperlink?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.Separator?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane prefHeight="400.0" prefWidth="500.0" style="-fx-background-color: #0288D1; -fx-border-color: #01579B; -fx-border-width: 5;" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="desktop_tasker.FXMLDocumentController">
<children>
<Label layoutX="215.0" layoutY="34.0" text="Sign In" textFill="WHITE">
<font>
<Font size="23.0" />
</font>
</Label>
<Hyperlink fx:id="link_login" layoutX="150.0" layoutY="269.0" onAction="#handleButtonAction" text="Not registered yet? Click here." textFill="WHITE" />
<TextField fx:id="et_username" layoutX="21.0" layoutY="102.0" prefHeight="25.0" prefWidth="425.0" promptText="Username" style="-fx-prompt-text-fill: #ffffff; -fx-background-color: #0288D1;" />
<Separator layoutX="27.0" layoutY="126.0" prefHeight="3.0" prefWidth="425.0" />
<Separator layoutX="27.0" layoutY="192.0" prefHeight="3.0" prefWidth="425.0" />
<Button fx:id="btn_signup" layoutX="27.0" layoutY="222.0" mnemonicParsing="false" onAction="#handleButtonAction" prefHeight="23.0" prefWidth="425.0" style="-fx-background-color: #FFA000; -fx-prompt-text-fill: #ffffff;" text="SignUp" textFill="WHITE" />
<PasswordField fx:id="et_password" layoutX="21.0" layoutY="167.0" prefHeight="25.0" prefWidth="425.0" promptText="Password" style="-fx-background-color: #0288D1; -fx-prompt-text-fill: #ffffff;" />
</children>
</AnchorPane>
And the other one:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="557.0" prefWidth="1012.0" style="-fx-background-color: #0288D1;" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="desktop_tasker.FXMLTaskerController">
<children>
<SplitPane dividerPositions="0.5811881188118811" layoutX="-8.0" layoutY="35.0" prefHeight="529.0" prefWidth="1027.0" style="-fx-background-color: #EEEEEE;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="28.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<ListView fx:id="list_todo" layoutY="-8.0" prefHeight="527.0" prefWidth="584.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<ListView fx:id="list_done" layoutY="14.0" prefHeight="527.0" prefWidth="420.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children></AnchorPane>
</items>
</SplitPane>
<MenuBar prefHeight="30.0" prefWidth="1012.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
As you can see I tried to use a controler and using a set pasing the String, the problem is that when I open the new scene, his controler resets and the String is no longer there, any idea why or how to solve this?

If you want to set a Controller with myLoader.setController(controler); you must do it before calling Pane myPane = (Pane)myLoader.load(); and also remove fx:controller="desktop_tasker.FXMLTaskerController" from FXMLTasker.fxml, else you get a LoadException: Controller value already specified.
See JavaDoc FXMLLoader.setController(Object controller):
Sets the controller associated with the root object. The value passed to this method is used as the value of the fx:controller attribute. This method must be called prior to loading the document when using controller event handlers when an fx:controller attribute is not specified in the document.
Alternatively you can request the Controller from FXMLLoader:
FXMLTaskerController controler = (FXMLTaskerController)myLoader.getController();
controler.setUser(et_username.getText());
But thereby you can't assume that username is set in initialize(URL url, ResourceBundle rb) and should removed from there.

Related

Root value already specified Exception in CustomController while loading a FXML

first of all: I have tried:
fxml loader exception "root value is already specified" I never specified a root value
javafx exception : Controller value already specified
LoadException: Root value already specified on custom control
But no solution worked for me: I deleted the fx:controller tag from my FXML -> Exception, added fx:root type="BorderPanealways the same Exception:
Caused by: java.lang.RuntimeException: javafx.fxml.LoadException: Root value already specified
When I remove the statement fxmlLoader.setRoot(this) from my custom controller no Exception is thrown but the layout is empty. For better understanding, below are my code snippets from my MainScreenController where I want to add the custom controller as child and my CustomController class ImageContainer
Help is appreciated!
Code snippet MainScreenController (only a snippet):
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{
ImageContainer imgC = new ImageContainer(4,2,"location");
fp_contentFlowPane.getChildren().add(imgC);
}
}}
Code of my Custom controller, ImageContainer:
public class ImageContainer extends Pane {
public HBox hbx_elementContainer;
public Label lb_likeCount;
public Label lb_commentCount;
public Label lb_location;
public Label lb_accountHolder;
public ImageView iv_feedImage;
private String imageLink;
public ImageContainer(int likeCount, int commentCount, String location) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/image_container.fxml"));
fxmlLoader.setController(this);
fxmlLoader.setRoot(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);
}
}
FXML file of the layout I want to set:
<?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">
<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>

Selecting exact row information and adding it to a text field from oblist

I have a program that is basically a task manager, it takes information from SQLite Database. it has 5 info fields (UID, Date, CreatedBy, Category, Task). In order to populate the table view I use class Model Table.
Controller
#FXML public TableView<ModelTable> taskManagerView;
#FXML public TableColumn<ModelTable, String> col_UID;
#FXML public TableColumn<ModelTable, String> col_Date;
#FXML public TableColumn<ModelTable, String> col_CreatedBy;
#FXML public TableColumn<ModelTable, String> col_Category;
#FXML public TableColumn<ModelTable, String> col_Task;
ObservableList<ModelTable> oblist = FXCollections.observableArrayList();
public FilteredList<ModelTable> filteredOblist = new FilteredList<>(oblist, s -> true);
try{
Connection conn =
DriverManager.getConnection("jdbc:sqlite://Location\\");
Statement statement = conn.createStatement();
ResultSet rs =statement.executeQuery("SELECT * FROM TaskManagerData");
while (rs.next()){
oblist.add(new ModelTable(rs.getString("UID"), rs.getString("Date"), rs.getString("CreatedBy"), rs.getString("Category"),rs.getString("Task")));
}
}catch (SQLException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("DB Error");
alert.setHeaderText("DB Connection Failed");
alert.setContentText(e.getMessage());
alert.showAndWait();
}
col_UID.setCellValueFactory(new PropertyValueFactory<>("UID"));
col_Date.setCellValueFactory(new PropertyValueFactory<>("Date"));
col_CreatedBy.setCellValueFactory(new PropertyValueFactory<>("CreatedBy"));
col_Category.setCellValueFactory(new PropertyValueFactory<>("Category"));
col_Task.setCellValueFactory(new PropertyValueFactory<>("Task"));
taskManagerView.setItems(filteredOblist);
ModelTable gettingTask =taskManagerView.getSelectionModel().getSelectedItem();
detailedTask.setText(gettingTask.getTask());
Model Table:
public class ModelTable {
String UID, Date, CreatedBy, Category, Task;
package Controllers;
public class ModelTable {
String UID, Date, CreatedBy, Category, Task;
public ModelTable(String UID, String date, String createdBy, String category, String task) {
this.UID = UID;
Date = date;
CreatedBy = createdBy;
Category = category;
Task = task;
}
public String getUID() {
return UID;
}
public void setUID(String UID) {
this.UID = UID;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getTask() {
return Task;
}
public void setTask(String task) {
Task = task;
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.DatePicker?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane prefHeight="488.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controllers.TaskManagerController">
<children>
<AnchorPane layoutY="3.0" prefHeight="165.0" prefWidth="600.0" AnchorPane.bottomAnchor="320.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="3.0">
<children>
<MenuBar layoutY="2.0" prefHeight="25.0" prefWidth="600.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="2.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Add Entry" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
<TextField fx:id="filter_uid" alignment="CENTER" layoutX="14.0" layoutY="62.0" promptText="UID" />
<TextField fx:id="filter_created" alignment="CENTER" layoutX="14.0" layoutY="98.0" promptText="Created By" />
<DatePicker fx:id="filter_date" layoutX="172.0" layoutY="98.0" onAction="#dateFilter" prefHeight="25.0" prefWidth="167.0" promptText="Date" />
<TextArea fx:id="detailedTask" editable="false" layoutX="348.0" layoutY="27.0" prefHeight="137.0" prefWidth="252.0" AnchorPane.leftAnchor="348.0" AnchorPane.rightAnchor="0.0" />
<RadioButton fx:id="radioHomework" layoutX="172.0" layoutY="79.0" mnemonicParsing="false" onAction="#radioButtonOne" text="Homework" />
<RadioButton fx:id="radioMaintenance" layoutX="172.0" layoutY="62.0" mnemonicParsing="false" onAction="#radioButtonTwo" text="Maintenance" />
<RadioButton fx:id="radioOther" layoutX="262.0" layoutY="62.0" mnemonicParsing="false" onAction="#radioButtonThree" text="Other" />
<RadioButton fx:id="radioNull" layoutX="262.0" layoutY="79.0" mnemonicParsing="false" onAction="#radioButtonFour" text="Show All" />
<Label layoutX="14.0" layoutY="39.0" prefHeight="17.0" prefWidth="326.0" style="-fx-alignment: CENTER;" text="FILTERS" textAlignment="CENTER">
<font>
<Font size="15.0" />
</font>
</Label>
</children></AnchorPane>
<TableView fx:id="taskManagerView" layoutY="166.0" prefHeight="282.0" prefWidth="600.0" AnchorPane.bottomAnchor="40.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="166.0">
<columns>
<TableColumn fx:id="col_UID" prefWidth="70.0" text="UID" />
<TableColumn fx:id="col_Date" prefWidth="100.0" text="Date" />
<TableColumn fx:id="col_CreatedBy" prefWidth="90.0" text="Created By" />
<TableColumn fx:id="col_Category" prefWidth="100.0" text="Category" />
<TableColumn fx:id="col_Task" prefWidth="239.0" text="Task" />
</columns>
</TableView>
<ButtonBar layoutY="360.0" prefHeight="40.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
<buttons>
<Button fx:id="addTask" mnemonicParsing="false" onAction="#addTaskFunction" text="Add Task" />
<Button fx:id="exportBtn" mnemonicParsing="false" onAction="#export" text="Export" />
<Button fx:id="backToMainMenu" mnemonicParsing="false" onAction="#backButton" text="Back" />
</buttons>
</ButtonBar>
</children>
</AnchorPane>
My question is how can i have it so my program when i select for example UID 7 (when the program is running) from the table view the information from "Task" appears in a text area in the program. Currently
Hopefully this was understandable.
Thank you.
The selection happens after the scene is displayed. If retrieved before (e.g. in the initialize method), the selectedItem property is null. Add a listener to the property to do the updates instead:
#FXML
private void initialize() {
taskManagerView.getSelectionModel().selectedItemProperty().addListener((o, oldValue, newValue) -> {
if (newValue == null) {
textArea.setText("");
// TODO: clear other controls
} else {
textArea.setText(newValue.getTask());
// TODO: set values to other controls
}
});
}

JavaFX fxml not launching/doing anything

I have built a GUI using scene builder, through eclipse.
I am trying to run the MainApp class to view the GUI in eclipse, everything compiles, there are no error messages in the console, a java process opens but nothing actually happens and no window is created on screen.
I have been through oracle's site and attempted to alter the code but nothing works. I have updated java, reinstalled javafx etc in eclipse. I also tried the program throuhg netbeans to the same effect.
Running on MacOS X
package main;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainApp extends Application {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(MainApp.class, (java.lang.String[])null);
}
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("GUI.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
`package main;
The controller class
public class Controller implements Initializable {
#FXML
Button checkButton;
#FXML
Button callButton;
#FXML
Button raiseButton;
#FXML
Button foldButton;
public void buttonClicked() {
System.out.println("Button was clicked");
}
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
}
}
The FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="800.0" style="-fx-background-color: #FFFFFF;" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="main.Controller">
<children>
<SplitPane dividerPositions="0.29949874686716793" layoutX="123.0" layoutY="67.0" prefHeight="433.0" prefWidth="800.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="67.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<LineChart layoutY="206.0" prefHeight="215.0" prefWidth="235.0">
<xAxis>
<CategoryAxis side="BOTTOM" />
</xAxis>
<yAxis>
<NumberAxis side="LEFT" />
</yAxis>
</LineChart>
<LineChart prefHeight="215.0" prefWidth="235.0">
<xAxis>
<CategoryAxis side="BOTTOM" />
</xAxis>
<yAxis>
<NumberAxis side="LEFT" />
</yAxis>
</LineChart>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<SplitPane dividerPositions="0.6783216783216783" orientation="VERTICAL" prefHeight="498.0" prefWidth="555.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0" />
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="127.0" prefWidth="553.0">
<children>
<TextArea disable="true" layoutX="9.0" layoutY="23.0" prefHeight="106.0" prefWidth="536.0" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="9.0" AnchorPane.rightAnchor="8.0" AnchorPane.topAnchor="23.0" />
<Label layoutX="14.0" layoutY="6.0" text="Live guidance:" />
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
</items>
</SplitPane>
<ImageView fitHeight="62.0" fitWidth="200.0" layoutX="14.0" layoutY="5.0">
<image>
<Image url="#../../../../../Desktop/Dissertation%20files/logo.jpg" />
</image>
</ImageView>
<ButtonBar layoutX="456.0" layoutY="16.0" prefHeight="40.0" prefWidth="200.0">
<buttons>
<Button fx:id="checkButton" mnemonicParsing="false" onAction="#buttonClicked" onMouseClicked="#buttonClicked" style="-fx-background-radius: 10;" text="Check" />
<Button fx:id="callButon" mnemonicParsing="false" onAction="#buttonClicked" onMouseClicked="#buttonClicked" style="-fx-background-radius: 10;" text="Call" />
<Button fx:id="raiseButton" mnemonicParsing="false" onAction="#buttonClicked" onMouseClicked="#buttonClicked" prefHeight="27.0" prefWidth="81.0" style="-fx-background-radius: 10;" text="Raise" />
<Button fx:id="foldButton" mnemonicParsing="false" onAction="#buttonClicked" onMouseClicked="#buttonClicked" style="-fx-background-radius: 10;" text="Fold" />
</buttons>
</ButtonBar>
</children>
</AnchorPane>
Apologies if I am missing something simple.
If the classes and the fxml file is under same package then the loader line should be like this
Parent root = FXMLLoader.load(getClass().getResource("/package_name/fxml2GUI.fxml"));
Put your source's package name in the place of "packagename"

javaFX getting null pointer while initiating controller

I am getting a null pointer exception while initializing a table.
This line controller.setUserDetailsList(userDetailsList) is throwing the error
even though I am adding data in userDetailsList.
Any Idea how to resolve this? Thanks..
public class Main extends Application {
private Stage primaryStage;
private ObservableList<UserDetails> userDetailsList = FXCollections.observableArrayList();
public Main() {
// Add some sample data
userDetailsList.add(new UserDetails("Hans"));
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
primaryStage.show();
primaryStage.setTitle("ICA");
loadMainViewPage();
}
private void loadMainViewPage(){
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("MainView.fxml"));
BorderPane mainView = (BorderPane) loader.load();
Scene scene = new Scene(mainView);
primaryStage.setScene(scene);
MainViewController controller = loader.getController();
controller.setUserDetailsList(userDetailsList);
}catch(Exception e) {
e.printStackTrace();
}
}
public ObservableList<UserDetails> getUserDetailsList() {
return userDetailsList;
}
public static void main(String[] args) {
launch(args);
}
}
Controller Class looks like this:
public class MainViewController {
#FXML
private TableView<UserDetails> userTable;
#FXML
private TableColumn<UserDetails,String> userNameColumn;
private Main main;
#FXML
private void initialize() {
System.out.println("inside initialize");
userNameColumn.setCellValueFactory(cellData -> cellData.getValue().HostNameProperty());
}
public void setUserDetailsList(ObservableList<UserDetails> userDetailsList) {
userTable.setItems(userDetailsList);
}
}
FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainViewController">
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
<center>
<AnchorPane>
<children>
<SplitPane dividerPositions="0.362876254180602" prefHeight="375.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<TableView fx:id="userTable">
<columns>
<TableColumn fx:id="userNameColumn" prefWidth="75.0" text="C1" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
<TextArea />
</items>
</SplitPane>
</children>
</AnchorPane>
</center>
</BorderPane>
Error:
java.lang.NullPointerException
at application.Main.loadMainViewPage(Main.java:48)
at application.Main.start(Main.java:30)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Why is ImageView not injected through JavaFX FXML?

I'm having a problem getting my ImageView component injected through FXMl in JavaFX. I have a controller written in Scala as so:
package me.mycontroller
import javafx.fxml.FXML
import java.util.ResourceBundle
import java.net.URL
import javafx.scene.image.ImageView
/**
* #author me
*/
class InvoiceController {
#FXML
private var resources: ResourceBundle = null
#FXML
private var location: URL = null
#FXML
private var imageBox2: ImageView = null
#FXML
def initialize() {
if(imageBox2==null) { throw new IllegalArgumentException("imageBox was null")}
}
}
and my FXMl is like so:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="286.0" prefWidth="512.0" xmlns:fx="http://javafx.com/fxml" fx:controller="me.mycontroller.InvoiceController">
<children>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="435.0" spacing="10.0" AnchorPane.bottomAnchor="58.0" AnchorPane.leftAnchor="38.5" AnchorPane.rightAnchor="38.5" AnchorPane.topAnchor="128.0">
<children>
<Label text="Invoice File" />
<TextField fx:id="fileField" prefWidth="200.0" />
</children>
</HBox>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="400.5" spacing="10.0" AnchorPane.bottomAnchor="-7.0" AnchorPane.leftAnchor="52.5" AnchorPane.rightAnchor="59.0" AnchorPane.topAnchor="193.0">
<children>
<AnchorPane prefHeight="100.0" prefWidth="376.0">
<children>
<AnchorPane layoutX="16.0" layoutY="0.0" prefHeight="100.0" prefWidth="294.0">
<children>
<Label layoutY="42.0" prefWidth="65.0" text="Supplier" AnchorPane.leftAnchor="25.0" />
<ChoiceBox fx:id="supplierDropDown" layoutY="40.0" prefWidth="200.0" AnchorPane.rightAnchor="5.0">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Item 1" />
<String fx:value="Item 2" />
<String fx:value="Item 3" />
</FXCollections>
</items>
</ChoiceBox>
</children>
</AnchorPane>
</children>
</AnchorPane>
</children>
</HBox>
<ImageView fx:id="imageBox2" fitHeight="105.99999961206467" fitWidth="141.3333282470703" layoutX="53.0" layoutY="22.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#../images/Regional.jpeg" />
</image>
</ImageView>
</children>
</AnchorPane>
When I run the program like:
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Invoice.fxml"));
I get an exception because imageBox2 is null. Any idea why it's not getting injected?
src/
main/
Main.java
MainLayoutController.java
main_layout.fxml
...
MainLayoutController.java:
public class MainLayoutController {
#FXML
private ImageView previewImage;
void setImage(Image img) {
previewImage.setImage(img);
}
}
main_layout.fxml:
<VBox ... fx:controller="main.MainLayoutController">
<children>
...
<ImageView fx:id="previewImage" ... />
</children>
</VBox>
Main.java:
public class Main extends Application {
private MainLayoutController mainLayoutController;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = fxmlLoader.load(
getClass().getResource("main_layout.fxml").openStream());
primaryStage.setScene(new Scene(root));
primaryStage.show();
mainLayoutController = fxmlLoader.getController();
mainLayoutController.setImage(...);
}
...
}

Categories