I'm developing a password manager program. When opening a new window in this program it throws an exception on the addEntry() mouse click event. I have a Main class that opens the main window (with sample.fxml) and a Controller class that manages to open the new window (with addNewEntryDialog.fxml). Here's my code:
Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
primaryStage.setTitle("Password Manager");
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
public class Controller implements Initializable {
public ObservableList<Data> data;
public TableView dbTable;
public TableColumn siteColumn, usernameColumn, passwordColumn;
public ToggleButton showPasswordToggle;
#Override
public void initialize(URL location, ResourceBundle resources) {
fillTable();
}
public void fillTable(){
data = FXCollections.observableArrayList();
String query = "SELECT * FROM accounts";
try {
Connection connection = connectToDatabase();
ResultSet resultSet = connection.createStatement().executeQuery(query);
while (resultSet.next()) {
data.add(new Data(resultSet.getString(1), resultSet.getString(2), resultSet.getString(3)));
}
siteColumn.setCellValueFactory(new PropertyValueFactory("site"));
usernameColumn.setCellValueFactory(new PropertyValueFactory("username"));
passwordColumn.setCellValueFactory(new PropertyValueFactory("password"));
dbTable.setItems(data);
} catch (SQLException e) {
e.printStackTrace();
}
}
#FXML
public void addEntry() throws IOException {
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/addEntryDialog.fxml"));
stage.setTitle("Add new entry");
stage.setScene(new Scene(root, 800, 600));
stage.show();
}
addEntryDialog.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="200.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<GridPane layoutX="28.0" layoutY="21.0" prefHeight="123.0" prefWidth="317.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label layoutX="33.0" layoutY="26.0" text="Site:" />
<Label layoutX="28.0" layoutY="78.0" text="Username:" GridPane.rowIndex="1" />
<Label layoutX="44.0" layoutY="135.0" text="Password:" GridPane.rowIndex="2" />
<TextField fx:id="siteField" layoutX="150.0" layoutY="21.0" GridPane.columnIndex="1" />
<TextField fx:id="usernameField" layoutX="150.0" layoutY="73.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<PasswordField fx:id="passwordField" layoutX="150.0" layoutY="123.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
</children>
</GridPane>
<Button layoutX="327.0" layoutY="163.0" mnemonicParsing="false" text="OK" />
<Button layoutX="246.0" layoutY="163.0" mnemonicParsing="false" text="Cancel" />
</children>
</Pane>
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<Pane prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<TableView fx:id="dbTable" layoutX="4.0" layoutY="85.0" prefHeight="505.0" prefWidth="790.0">
<columns>
<TableColumn fx:id="siteColumn" prefWidth="263.0" text="Site" />
<TableColumn fx:id="usernameColumn" prefWidth="263.0" text="Username" />
<TableColumn fx:id="passwordColumn" prefWidth="263.0" text="Password" />
</columns>
</TableView>
<GridPane layoutX="14.0" layoutY="27.0" prefHeight="25.0" prefWidth="263.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Button fx:id="addNewEntry" layoutX="14.0" layoutY="14.0" mnemonicParsing="false" onMouseClicked="#addEntry" text="Add.." GridPane.columnIndex="0" />
<Button fx:id="removeEntry" layoutX="83.0" layoutY="14.0" mnemonicParsing="false" text="Remove.." GridPane.columnIndex="1" />
<Button fx:id="editEntry" layoutX="178.0" layoutY="14.0" mnemonicParsing="false" text="Edit.." GridPane.columnIndex="2" />
</children>
</GridPane>
<ToggleButton fx:id="showPasswordToggle" layoutX="671.0" layoutY="27.0" mnemonicParsing="false" text="Show Password" />
</children>
</Pane>
STACK TRACE
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 31 more
Caused by: javafx.fxml.LoadException:
/home/umberto/passwordManager/out/production/passwordManager/addEntryDialog.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.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at sample.Controller.addEntry(Controller.java:58)
... 41 more
Caused by: java.lang.NullPointerException
at sample.Controller.loadTableData(Controller.java:45)
at sample.Controller.initialize(Controller.java:30)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 49 more
Look at your addEntryDialog.fxml file. There is definition of this view's controller:
<Pane ... fx:controller="sample.Controller>
JavaFX loads the view, looks for the controller and creates it. (At this moment another sample.Controller object is instantiated). After creating it sees that this controller implements Initializable interface, so it executes initialize method which in turn calls fillTable method and finally the statement siteColumn.setCellValueFactory(..) is reached. The problem is that there's no siteColumn for addEntryDialog.fxml view - it has not been binded since there's no element on view with that id.
Solution is to create proper controller for addEntryView.fxml and call it in xml fx:controller attribute.
Related
So I was given code from the textbook to use in eclipse and it actually won't run the base code even though I did everything the professor told me to do. Im getting an error exception running application application.TipCalculator and I have no idea what to do. First code snippet is my main, second is my controller, third is my xml file.
TipCalculator.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TipCalculator extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/TipCalculator.fxml"));
Scene scene = new Scene(root); // attach scene graph to scene
stage.setTitle("Tip Calculator"); // displayed in window's title bar
stage.setScene(scene); // attach scene to stage
stage.show(); // display the stage
}
public static void main(String[] args) {
// create a TipCalculator object and call its start method
launch(args);
}
}
TipCalculatorController.java
package application;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
public class TipCalculatorController {
// formatters for currency and percentages
private static final NumberFormat currency =
NumberFormat.getCurrencyInstance();
private static final NumberFormat percent =
NumberFormat.getPercentInstance();
private BigDecimal tipPercentage = new BigDecimal(0.15); // 15% default
// GUI controls defined in FXML and used by the controller's code
#FXML
private TextField amountTextField;
#FXML
private Label tipPercentageLabel;
#FXML
private Slider tipPercentageSlider;
#FXML
private TextField tipTextField;
#FXML
private TextField totalTextField;
// calculates and displays the tip and total amounts
#FXML
private void calculateButtonPressed(ActionEvent event) {
try {
BigDecimal amount = new BigDecimal(amountTextField.getText());
BigDecimal tip = amount.multiply(tipPercentage);
BigDecimal total = amount.add(tip);
tipTextField.setText(currency.format(tip));
totalTextField.setText(currency.format(total));
}
catch (NumberFormatException ex) {
amountTextField.setText("Enter amount");
amountTextField.selectAll();
amountTextField.requestFocus();
}
}
// called by FXMLLoader to initialize the controller
public void initialize() {
// 0-4 rounds down, 5-9 rounds up
currency.setRoundingMode(RoundingMode.HALF_UP);
// listener for changes to tipPercentageSlider's value
tipPercentageSlider.valueProperty().addListener(
new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov,
Number oldValue, Number newValue) {
tipPercentage =
BigDecimal.valueOf(newValue.intValue() / 100.0);
tipPercentageLabel.setText(percent.format(tipPercentage));
}
}
);
}
}
TipCalculator.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane hgap="8.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-
Infinity" minWidth="-Infinity"
xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="application.TipCalculatorController">
<columnConstraints>
<ColumnConstraints halignment="RIGHT" hgrow="SOMETIMES" minWidth="10.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label text="Amount" />
<Label fx:id="tipPercentageLabel" text="15%" GridPane.rowIndex="1" />
<Label text="Tip" GridPane.rowIndex="2" />
<Label text="Total" GridPane.rowIndex="3" />
<TextField fx:id="amountTextField" GridPane.columnIndex="1" />
<TextField fx:id="tipTextField" editable="false" focusTraversable="false" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<TextField fx:id="totalTextField" editable="false" focusTraversable="false" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<Slider fx:id="tipPercentageSlider" blockIncrement="5.0" max="30.0" value="15.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Button maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#calculateButtonPressed" text="Calculate" GridPane.columnIndex="1" GridPane.rowIndex="4" />
</children>
<padding>
<Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
</padding>
</GridPane>
The error im getting is:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: javafx.fxml.LoadException:
/C:/Users/Bandi/eclipse-workspace/TipCalculator/bin/TipCalculator.fxml:41
at javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
at application.TipCalculator.start(TipCalculator.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Caused by: java.lang.NumberFormatException: For input string: "- Infinity"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at java.base/java.lang.Double.valueOf(Double.java:512)
at javafx.fxml/com.sun.javafx.fxml.BeanAdapter.coerce(BeanAdapter.java:450)
at javafx.fxml/com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:258)
at javafx.fxml/com.sun.javafx.fxml.BeanAdapter.put(BeanAdapter.java:54)
at javafx.fxml/javafx.fxml.FXMLLoader$Element.applyProperty(FXMLLoader.java:520)
at javafx.fxml/javafx.fxml.FXMLLoader$Element.processValue(FXMLLoader.java:370)
at javafx.fxml/javafx.fxml.FXMLLoader$Element.processPropertyAttribute(FXMLLoader.java:332)
at javafx.fxml/javafx.fxml.FXMLLoader$Element.processInstancePropertyAttributes(FXMLLoader.java:242)
at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:775)
at javafx.fxml/javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2838)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2557)
... 17 more
Exception running application application.TipCalculator
Please help.
firstly you need to change the controller which you added in application package:
note: the / make it to read from the src folder because they are not in the same package.
TipController
change this:
Parent root = FXMLLoader.load(getClass().getResource("TipCalculator.fxml"));
to
Parent root = FXMLLoader.load(getClass().getResource("/TipCalculator.fxml"));
then change the fxml file where you specified the path of controller:
TipCalculator.fxml
<GridPane hgap="8.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.TipCalculatorController">
Complete Code:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane hgap="8.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.TipCalculatorController">
<columnConstraints>
<ColumnConstraints halignment="RIGHT" hgrow="SOMETIMES" minWidth="10.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label text="Amount" />
<Label fx:id="tipPercentageLabel" text="15%" GridPane.rowIndex="1" />
<Label text="Tip" GridPane.rowIndex="2" />
<Label text="Total" GridPane.rowIndex="3" />
<TextField fx:id="amountTextField" GridPane.columnIndex="1" />
<TextField fx:id="tipTextField" editable="false" focusTraversable="false" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<TextField fx:id="totalTextField" editable="false" focusTraversable="false" GridPane.columnIndex="1" GridPane.rowIndex="3" />
<Slider fx:id="tipPercentageSlider" blockIncrement="5.0" max="30.0" value="15.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Button maxWidth="1.7976931348623157E308" mnemonicParsing="false" onAction="#calculateButtonPressed" text="Calculate" GridPane.columnIndex="1" GridPane.rowIndex="4" />
</children>
<padding>
<Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
</padding>
</GridPane>
I have a vbox which contains a list of cards(Anchor panes). I am trying to make each card draggable so that I can change the order of the list whenever I want. I am using a scene builder.
However, I keep getting the following message after I drag and attempt to drop.
Java Messsge:class javafx.scene.layout.VBox cannot be cast to class javafx.scene.layout.AnchorPane(javafx.scene.layout.VBox and javafx.scene.layout.AnchorPane are in module javafx.graphics of loader 'app')
My code:
minimal code provided only contains two cards, one of which is being used only in my code.
Edit: I no longer get the error message however, I am not getting my desired result as the cards are not changing positions
mport javafx.beans.property.ObjectProperty;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TitledPane;
import javafx.scene.image.WritableImage;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Controller
{
#FXML public AnchorPane card1, card2;
#FXML public AnchorPane current;
#FXML public GridPane gridPane;
#FXML public GridPane column1;
#FXML public AnchorPane col1;
#FXML public Button button1, button2;
#FXML public Button currentButton;
#FXML public VBox v1;
#FXML
public void detect() { //detect card
card1.setOnDragDetected((MouseEvent event) -> { //card1 is the card
Dragboard db = card1.startDragAndDrop(TransferMode.MOVE);
ClipboardContent content = new ClipboardContent();
content.putString(card1.getId());
WritableImage snapshot = card1.snapshot(new SnapshotParameters(), null);
db.setDragView(snapshot);
db.setContent(content);
event.consume();
});
}
#FXML
public void accept() { //add to vbox
v1.addEventHandler(DragEvent.DRAG_OVER, (DragEvent event) -> { //v1 is the vbox
if (event.getGestureSource() != v1
&& event.getDragboard().hasString()) {
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
});
}
#FXML
public void drop() {
v1.addEventHandler(DragEvent.DRAG_DROPPED, (DragEvent event) -> {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
VBox parent = (VBox) card1.getParent();
//int targetIndex = parent.getChildren().indexOf(card1);
List<Node> nodes = new ArrayList<Node>(parent.getChildren());
parent.getChildren().clear();
parent.getChildren().addAll(nodes);
success = true;
}
event.setDropCompleted(success);
event.consume();
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="772.0" prefWidth="1295.0" style="-fx-background-color: #C5F5D4;" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="KanbanBoard.Controller">
<children>
<AnchorPane layoutY="47.0" prefHeight="687.0" prefWidth="1295.0">
<children>
<AnchorPane fx:id="col1" layoutX="-1.0" prefHeight="724.0" prefWidth="216.0">
<children>
<GridPane fx:id="column1" layoutX="33.0" layoutY="15.0" onMouseDragOver="#accept" prefHeight="724.0" prefWidth="209.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="7.0" AnchorPane.topAnchor="0.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints maxHeight="353.8666748046875" minHeight="10.0" prefHeight="103.20001831054685" vgrow="SOMETIMES" />
<RowConstraints maxHeight="621.5999816894531" minHeight="10.0" prefHeight="621.5999816894531" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<VBox fx:id="v1" onDragDropped="#drop" onDragOver="#accept" prefHeight="200.0" prefWidth="210.0" GridPane.rowIndex="1">
<children>
<AnchorPane fx:id="card1" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onDragDetected="#detect" onMouseDragged="#handleLabel" prefHeight="125.0" prefWidth="198.0" style="-fx-background-color: #E5EAE6;">
<children>
<TextField layoutX="5.0" layoutY="3.0" prefHeight="26.0" prefWidth="65.0" promptText="ID" />
<TextField layoutX="72.0" layoutY="3.0" prefHeight="26.0" prefWidth="124.0" promptText="Title" />
<TextArea layoutX="5.0" layoutY="32.0" prefHeight="50.0" prefWidth="190.0" promptText="Description" />
<TextField layoutX="5.0" layoutY="85.0" prefHeight="26.0" prefWidth="124.0" promptText="Story point" />
<Button fx:id="button1" layoutX="164.0" layoutY="85.0" mnemonicParsing="false" onMouseClicked="#removeCard" prefHeight="24.0" prefWidth="31.0" style="-fx-background-color: #ECF4EE;" text="-" />
<Button layoutX="129.0" layoutY="85.0" mnemonicParsing="false" prefHeight="24.0" prefWidth="31.0" style="-fx-background-color: #ECF4EE;" text="+" />
</children>
</AnchorPane>
<AnchorPane fx:id="card2" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onDragDetected="#detect" onMouseClicked="#handleLabel" prefHeight="125.0" prefWidth="198.0" style="-fx-background-color: #E5EAE6;">
<children>
<TextField layoutX="5.0" layoutY="3.0" prefHeight="26.0" prefWidth="65.0" promptText="ID" />
<TextField layoutX="72.0" layoutY="3.0" prefHeight="26.0" prefWidth="124.0" promptText="Title" />
<TextArea layoutX="5.0" layoutY="32.0" prefHeight="50.0" prefWidth="190.0" promptText="Description" />
<TextField layoutX="5.0" layoutY="85.0" prefHeight="26.0" prefWidth="124.0" promptText="Story point" />
<Button fx:id="button2" layoutX="164.0" layoutY="85.0" mnemonicParsing="false" onMouseClicked="#removeCard" prefHeight="24.0" prefWidth="31.0" style="-fx-background-color: #ECF4EE;" text="-" />
<Button layoutX="129.0" layoutY="85.0" mnemonicParsing="false" prefHeight="24.0" prefWidth="31.0" style="-fx-background-color: #ECF4EE;" text="+" />
</children>
</AnchorPane>
</children>
</VBox>
<Pane prefHeight="98.0" prefWidth="226.0" style="-fx-background-color: #D1D3D1;">
<children>
<Button layoutX="124.0" layoutY="64.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="26.0" text="-" />
<TextArea layoutY="39.0" prefHeight="50.0" prefWidth="124.0" promptText="Role" />
<TextField layoutX="1.0" layoutY="5.0" prefHeight="26.0" prefWidth="124.0" promptText="Name" />
<Button fx:id="addColumnButton" layoutX="124.0" layoutY="36.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="26.0" text="+" />
</children>
</Pane>
</children>
</GridPane>
</children>
</AnchorPane>
<AnchorPane layoutX="1082.0" prefHeight="726.0" prefWidth="213.0">
<children>
<Pane prefHeight="50.0" prefWidth="214.0" style="-fx-background-color: #8F9691;">
<children>
<Label layoutX="49.0" layoutY="7.0" prefHeight="36.0" prefWidth="46.0" text="Log" textAlignment="CENTER" textOverrun="WORD_ELLIPSIS">
<font>
<Font size="22.0" />
</font>
</Label>
</children>
</Pane>
<Pane layoutY="49.0" prefHeight="676.0" prefWidth="214.0" style="-fx-background-color: #C6C8C6;" />
</children>
</AnchorPane>
<GridPane fx:id="gridPane" layoutX="228.0" onDragDropped="#drop" onDragOver="#accept" prefHeight="726.0" prefWidth="856.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints maxHeight="627.1999938964843" minHeight="10.0" prefHeight="622.4000061035156" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>
</children>
</AnchorPane>
<Label layoutX="381.0" layoutY="-4.0" prefHeight="50.0" prefWidth="180.0" text="Kanban Board">
<font>
<Font size="28.0" />
</font>
</Label>
</children>
</AnchorPane>
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.*;
import javafx.stage.Stage;
import java.io.IOException;
public class Kanban extends Application {
//private Button b;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("Kanban.fxml"));
} catch (IOException e) {
throw new RuntimeException(e);
}
Controller controller = new Controller();
FXMLLoader loader = new FXMLLoader();
loader.setController(controller);
//Controller c = loader.getController();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Can someone help me out please.
AnchorPane parent = (AnchorPane) card1.getParent(); (In the drop() method, at the bottom of your code)
card1.getParent() with a type of VBox cannot be cast to AnchorPane
For a project I need to create a GUI using JavaFX. So with a tutorial of Scene Builder/JavaFX that I followed very closely I created a very basic GUI. But the load doesn't seem to work and throws an LoadException. I've seem a few similar problems online, but none of their answers seemed to fix mine. I have done as much googleFoo as I can trying similar guides and tutorials, but it just won't load.
Here is main:
package stacksim;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class stacksim extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
// Read file fxml and draw interface.
Parent root = FXMLLoader.load(getClass()
.getResource("stacksim.fxml"));
primaryStage.setTitle("Stack Simulation");
primaryStage.setScene(new Scene(root));
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Controller:
package stacksim;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.transform.Translate;
/**
* FXML Controller class
*
* #author Dell
*/
public class stacksimcontroller implements Initializable {
#FXML
private Button btnPush;
#FXML
private Button btnPop;
#FXML
private Button btnExit;
#FXML
private GridPane gridBoxBall;
#FXML
private GridPane gridBoxNum;
#FXML
private Label description;
private int curColumn = 0;
private int count = 0;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void actionPush(ActionEvent event) {
System.out.println("Button Push Clicked!");
if (curColumn >= 10) {
description.setText("Stack is fully, you can't push more !");
} else {
addCircle(curColumn, 0);
addLabel(curColumn, 0);
System.out.println(' ');
count++;
description.setText("Push successfully!");
curColumn++;
System.out.println(curColumn);
}
}
public void actionPop(ActionEvent event) {
System.out.println("Button Pop Clicked!");
if (curColumn == 0) {
description.setText("Stack Empty! Nothing to pop!");
System.out.println(curColumn);
} else if (curColumn == 1) {
curColumn--;
gridBoxBall.getChildren().remove(curColumn);
gridBoxNum.getChildren().remove(curColumn);
description.setText("Pop successfully!");
System.out.println(curColumn);
} else {
curColumn--;
gridBoxBall.getChildren().remove(curColumn);
gridBoxNum.getChildren().remove(curColumn);
System.out.println(curColumn);
for (int i = 0; i < curColumn; i++) {
Translate translate = new Translate();
translate.setZ(0);
translate.setY(0);
translate.setX(0);
gridBoxBall.getChildren().get(i).getTransforms().addAll(translate);
gridBoxNum.getChildren().get(i).getTransforms().addAll(translate);
}
description.setText("Pop successfully!");
}
}
public void actionExit(ActionEvent event) {
System.exit(0);
}
public void addCircle(int col, int row){
Circle circle = new Circle(20);
circle.setFill(Color.FIREBRICK);
gridBoxBall.add(circle, col, row);
}
public void addLabel(int col, int row){
Label label = new Label(count + "");
label.setPrefSize(40, 40);
label.setAlignment(Pos.CENTER);
gridBoxNum.add(label, col, row);
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.shape.*?>
<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?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="queuedemon.QueueDemonController">
<children>
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="-4.0" layoutY="-3.0" prefHeight="65.0" prefWidth="606.0" text="STACK HAVING 10 SLOTS" textFill="FIREBRICK">
<font>
<Font name="Arial Bold" size="26.0" />
</font>
</Label>
<HBox alignment="CENTER" layoutX="1.0" layoutY="335.0" prefHeight="51.0" prefWidth="600.0" spacing="100.0">
<children>
<Button fx:id="btnPush" alignment="CENTER" mnemonicParsing="false" onAction="#actionPush" text="PUSH" textFill="FIREBRICK" />
<Button fx:id="btnPop" alignment="CENTER" mnemonicParsing="false" onAction="#actionPop" text="POP" textFill="FIREBRICK" />
</children>
<opaqueInsets>
<Insets />
</opaqueInsets>
<padding>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
</padding>
</HBox>
<Label fx:id="description" alignment="CENTER" layoutX="2.0" layoutY="281.0" prefHeight="17.0" prefWidth="600.0" textFill="FIREBRICK">
<font>
<Font size="14.0" />
</font>
</Label>
<GridPane fx:id="gridBoxBall" hgap="10.0" layoutX="62.0" layoutY="180.0" prefHeight="40.0" prefWidth="500.0" AnchorPane.bottomAnchor="180.0" AnchorPane.leftAnchor="62.0" AnchorPane.rightAnchor="38.0" AnchorPane.topAnchor="180.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<padding>
<Insets left="10.0" right="10.0" />
</padding>
</GridPane>
<GridPane fx:id="gridBoxNum" hgap="10.0" layoutX="62.0" layoutY="241.0" prefHeight="40.0" prefWidth="500.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<padding>
<Insets left="10.0" right="10.0" />
</padding>
</GridPane>
<Button fx:id="btnExit" alignment="CENTER" layoutX="537.0" layoutY="14.0" mnemonicParsing="false" onAction="#actionExit" text="EXIT" textFill="FIREBRICK" />
</children>
</AnchorPane>
error:
javafx.fxml.LoadException:
/E:/Study/OOP/Java/JavaMidterm/TestQueueMidterm/bin/stacksim/stacksim.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2848)
at javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2692)
at javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2661)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2517)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at stacksim.stacksim.start(stacksim.java:31)
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(Unknown Source)
Caused by: java.lang.ClassNotFoundException
at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2899)
at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)
... 20 more
I'm a new javaFx with Scenebuilder and MVC starter.
I have a problem as below:
I tried to make a main window to alert a new window. And I tried to midified the label text in that alert window. But I cannot do that. And I got this error:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 48 more
Caused by: java.lang.NullPointerException
at controller.AlertController.setAlertLabel(AlertController.java:36)
at controller.MainController.onMainButtonClicked(MainController.java:24)
... 58 more
I have a main window with maincontroller, alertController and main.fxml and alert.fxml as below:
Main:
package app;
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("../view/Main.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Main Controller:
package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class MainController {
AlertController alertController = new AlertController();
#FXML
public Label mainLabel;
#FXML
public TextField mainTextField;
#FXML
public Button mainButton;
#FXML
public void onMainButtonClicked() {
alertController.displayAlert();
alertController.setAlertLabel("Hello from MainController!");
}
}
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.MainController">
<children>
<VBox prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<HBox alignment="CENTER" prefHeight="154.0" prefWidth="600.0">
<children>
<Label fx:id="mainLabel" alignment="CENTER" contentDisplay="TOP" prefHeight="31.0" prefWidth="115.0" text="Main Text" />
</children>
</HBox>
<HBox alignment="CENTER" centerShape="false" layoutX="10.0" layoutY="10.0">
<children>
<TextField fx:id="mainTextField" alignment="TOP_LEFT" prefHeight="25.0" prefWidth="331.0" />
</children>
</HBox>
<HBox alignment="CENTER" layoutX="10.0" layoutY="10.0" prefHeight="100.0" prefWidth="200.0">
<children>
<Button fx:id="mainButton" mnemonicParsing="false" onAction="#onMainButtonClicked" text="Display Alert && Set Message Text" />
</children>
</HBox>
</children>
</VBox>
</children>
</AnchorPane>
AlertController:
package controller;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.io.IOException;
public class AlertController {
Stage window;
#FXML
public Label alertLabel;
#FXML
Button alertButton;
public void displayAlert() {
try {
window = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("../view/Alert.fxml"));
Scene scene = new Scene(root);
window.setScene(scene);
window.setTitle("Alert");
window.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setAlertLabel(String str) {
alertLabel.setText(str);
}
#FXML
public void onAlertButtonClicked() {
window.close();
}
}
And Alert.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="210.0" prefWidth="380.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.AlertController">
<children>
<VBox prefHeight="210.0" prefWidth="380.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<HBox alignment="BOTTOM_CENTER" prefHeight="100.0" prefWidth="200.0">
<children>
<Label fx:id="alertLabel" text="Alert Message" />
</children>
</HBox>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
<children>
<Button fx:id="alertButton" mnemonicParsing="false" onAction="#onAlertButtonClicked" text="Close" />
</children>
</HBox>
</children>
</VBox>
</children>
</AnchorPane>
Please kindly help me solve this problems and explain me why this doesn't work. Thank you for you suggestions.
There are two instances of AlertController: the one you create in MainController with
AlertController alertController = new AlertController();
and the one that is created by the FXMLLoader when you load Alert.fxml in displayAlert().
The #FXML-annotated fields are initialized by the FXMLLoader on the instance it creates. However, you are calling setAlertLabel(...) on an instance of AlertController that was not created by the FXMLLoader. So when you call
alertController.setAlertLabel("Hello from MainController!");
the alertLabel belonging to alertController has not been initialized, and you get a null pointer exception.
Simple Solution
The easiest fix is to load Alert.fxml in MainController, and retrieve the correct controller instance:
public class MainController {
#FXML
public Label mainLabel;
#FXML
public TextField mainTextField;
#FXML
public Button mainButton;
#FXML
public void onMainButtonClicked() {
FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/Alert.fxml"));
Parent root = loader.load();
AlertController alertController = loader.getController();
alertController.setAlertLabel("Hello from MainController!");
Scene scene = new Scene(root);
window.setScene(scene);
window.setTitle("Alert");
window.show();
}
}
and remove the displayAlert() method from AlertController.
Custom Component Solution
An alternative, which is structurally a bit closer to your original, is to replace the AlertController with a custom component.
Alert.fxml (note the change to the root element, and that fx:controller has been removed):
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<fx:root type="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="210.0" prefWidth="380.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" >
<children>
<VBox prefHeight="210.0" prefWidth="380.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<HBox alignment="BOTTOM_CENTER" prefHeight="100.0" prefWidth="200.0">
<children>
<Label fx:id="alertLabel" text="Alert Message" />
</children>
</HBox>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
<children>
<Button fx:id="alertButton" mnemonicParsing="false" onAction="#onAlertButtonClicked" text="Close" />
</children>
</HBox>
</children>
</VBox>
</children>
</fx:root>
AlertController.java:
package controller;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.io.IOException;
public class AlertController extends AnchorPane {
Stage window;
#FXML
public Label alertLabel;
#FXML
Button alertButton;
public AlertController() {
window = new Stage();
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/Alert.fxml"));
loader.setController(this);
loader.setRoot(this);
loader.load();
Scene scene = new Scene(this);
window.setScene(scene);
window.setTitle("Alert");
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayAlert() {
window.show();
}
public void setAlertLabel(String str) {
alertLabel.setText(str);
}
#FXML
public void onAlertButtonClicked() {
window.close();
}
}
and now your main controller can look like this:
package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class MainController {
AlertController alertController = new AlertController();
#FXML
public Label mainLabel;
#FXML
public TextField mainTextField;
#FXML
public Button mainButton;
#FXML
public void onMainButtonClicked() {
alertController.displayAlert();
alertController.setAlertLabel("Hello from MainController!");
}
}
I am creating a bidding system where a scene has the list of items available for auction. when the user clicks on the item, the scene should change to another anchorpane where all the details related to the item will displayed. When I click on the item I get this exception:
javafx.fxml.LoadException:
/C:/Users/Deepak95/IdeaProjects/Package2/out/production/Package2/System/view/ItemView.fxml:9
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2605)
at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:104)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:928)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:967)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:216)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:740)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2711)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2531)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2445)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2413)
at System.Main.showItem(Main.java:61)
at System.View.ItemOverviewController.lambda$initialize$2(ItemOverviewController.java:23)
at System.View.ItemOverviewController$$Lambda$154/21527645.changed(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyObjectWrapper.java:176)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:142)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:102)
at javafx.scene.control.MultipleSelectionModelBase.lambda$new$34(MultipleSelectionModelBase.java:67)
at javafx.scene.control.MultipleSelectionModelBase$$Lambda$135/26372034.invalidated(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:176)
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:142)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:113)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:147)
at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:68)
at javafx.scene.control.TableView$TableViewArrayListSelectionModel.updateSelectedIndex(TableView.java:2900)
at javafx.scene.control.TableView$TableViewArrayListSelectionModel.select(TableView.java:2430)
at javafx.scene.control.TableView$TableViewArrayListSelectionModel.clearAndSelect(TableView.java:2360)
at javafx.scene.control.TableView$TableViewSelectionModel.clearAndSelect(TableView.java:1898)
at com.sun.javafx.scene.control.behavior.TableCellBehaviorBase.simpleSelect(TableCellBehaviorBase.java:215)
at com.sun.javafx.scene.control.behavior.TableCellBehaviorBase.doSelect(TableCellBehaviorBase.java:148)
at com.sun.javafx.scene.control.behavior.CellBehaviorBase.mousePressed(CellBehaviorBase.java:150)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:95)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3758)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3486)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2495)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:385)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$255/19643353.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:927)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$38/10455932.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.InstantiationException: System.View.ItemViewController
at java.lang.Class.newInstance(Class.java:427)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:923)
... 72 more
Caused by: java.lang.NoSuchMethodException: System.View.ItemViewController.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 74 more
Here are the functions responsible for the scene change:
public void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showItemOverview(){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/ItemOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
rootLayout.setCenter(personOverview);
ItemOverviewController controller=loader.getController();
controller.setMain(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showItem(Item I){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/ItemView.fxml"));
AnchorPane itemview= (AnchorPane) loader.load();
rootLayout.setCenter(itemview);
ItemViewController controller=loader.getController();
controller.setMain(this);
}catch(IOException e){
e.printStackTrace();
}
}
Here is the overview class and its corresponding fxml file:
package System.View;
import System.Main;
import System.Model.Item;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class ItemOverviewController {
#FXML
private TableView<Item> itemTableView;
#FXML
private TableColumn<Item,String> itemnamecolumn;
#FXML
private TableColumn<Item,Integer> basepricecolumn;
private Main main;
public ItemOverviewController(){
}
#FXML
private void initialize(){
itemnamecolumn.setCellValueFactory(celldata->celldata.getValue().itemnameProperty());
basepricecolumn.setCellValueFactory(celldata->celldata.getValue().initialpriceProperty().asObject());
itemTableView.getSelectionModel().selectedItemProperty().addListener((observable,oldvalue,newvalue)->main.showItem(newvalue));
}
public void setMain(Main main){
this.main=main;
itemTableView.setItems(main.getItemdata());
}
}
fxml file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="375.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="System.View.ItemOverviewController">
<children>
<TableView fx:id="itemTableView" layoutX="200.0" layoutY="86.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="itemnamecolumn" prefWidth="310.0" text="Item Name" />
<TableColumn fx:id="basepricecolumn" prefWidth="289.0" text="BasePrice" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>
</children>
</AnchorPane>
And the itemview controller class and its fxml file:
package System.View;
import System.Model.Item;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import System.Main;
public class ItemViewController {
Item I;
#FXML
Label itemname;
#FXML
Label description;
#FXML
Label biddername;
#FXML
Label baseprice;
#FXML
Label currentprice;
Main main;
public ItemViewController(Item I){
this.I=I;
}
public void initialize(){
itemname.setText(I.getItemname());
description.setText(I.getDescription());
biddername.setText(I.getBiddername());
baseprice.setText(I.getInitialprice().toString());
currentprice.setText(I.getInitialprice().toString());
}
public void setMain(Main main) {
this.main = main;
}
}
fxml file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="300.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="System.View.ItemViewController">
<children>
<SplitPane dividerPositions="0.5" layoutX="159.0" layoutY="46.0" prefHeight="300.0" prefWidth="600.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="160.0" prefWidth="100.0">
<children>
<SplitPane dividerPositions="0.5" orientation="VERTICAL" prefHeight="298.0" prefWidth="296.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">
<children>
<ImageView fitHeight="150.0" fitWidth="296.0" layoutX="-22.0" layoutY="-2.0" pickOnBounds="true" preserveRatio="true" 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="100.0" prefWidth="160.0">
<children>
<GridPane prefHeight="145.0" prefWidth="294.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label text="Base price:">
<font>
<Font size="20.0" />
</font>
</Label>
<Label text="Current Price:" GridPane.rowIndex="1">
<font>
<Font size="20.0" />
</font>
</Label>
<Label text="Bidder Name:" GridPane.rowIndex="2">
<font>
<Font size="20.0" />
</font>
</Label>
<Label fx:id="baseprice" text="Label" GridPane.columnIndex="1">
<font>
<Font size="20.0" />
</font>
</Label>
<Label fx:id="currentprice" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="1">
<font>
<Font size="20.0" />
</font>
</Label>
<Label fx:id="biddername" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="2">
<font>
<Font size="20.0" />
</font>
</Label>
</children>
</GridPane>
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<Label layoutX="14.0" layoutY="14.0" text="Item Name:">
<font>
<Font size="20.0" />
</font>
</Label>
<Label fx:id="itemname" layoutX="134.0" layoutY="14.0" text="Label">
<font>
<Font size="20.0" />
</font>
</Label>
<Label fx:id="description" layoutX="14.0" layoutY="56.0" prefHeight="176.0" prefWidth="233.0" text="Label" />
<ButtonBar layoutX="81.0" layoutY="244.0" prefHeight="40.0" prefWidth="200.0">
<buttons>
<Button mnemonicParsing="false" text="Return" />
<Button mnemonicParsing="false" text="Bid" />
</buttons>
</ButtonBar>
</children></AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
Thanks in advance for the help :D
Edit: Inserted the packages as asked