0

I am attempting to capture the TextField and Control Field values entered from the addItems.java class. Then display that data on the TableView generated on the shoppingCartController.java class. I do not get an error message when I hit add on the addItems.java file, but when I go back to the main shoppingCartController scene the entered data is not there.

Below is what is called when the 'Add' button is selected:

   public void handleitemAdd(ActionEvent event) throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("additems.fxml"));
        Parent addItem_page = loader.load();

        ObservableList<Products> list = FXCollections.observableArrayList();

        list.add(new Products(productPriority.toString(),
                productName.getText(),
                Double.parseDouble(productPrice.getText()),
                Integer.parseInt(productQty.getText())));
        table.getItems().add(list);

        System.out.println("Displaying information to consoles: Ensuring the addItem method worked as expected.");
    }

Any assistance in reviewing this issue would be appreciated.

addItems.java

package shoppingcart;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class addItems implements Initializable {

    // Fields used to add items to cart
    @FXML private TextField productName = new TextField();
    @FXML private TextField productQty = new TextField();
    @FXML private TextField productPrice = new TextField();
    @FXML private ChoiceBox productPriority = new ChoiceBox();

    // Create the TableView
    TableView table = new TableView(shoppingCartController.getProduct());

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        //Used to Initialize the Scene
    }

    public void handleitemAdd(ActionEvent event) throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("additems.fxml"));
        Parent addItem_page = loader.load();

        ObservableList<Products> list = FXCollections.observableArrayList();

        list.add(new Products(productPriority.toString(),
                productName.getText(),
                Double.parseDouble(productPrice.getText()),
                Integer.parseInt(productQty.getText())));
        table.getItems().add(list);

        System.out.println("Displaying information to consoles: Ensuring the addItem method worked as expected.");
    }

    public void handleitemReturnCart(ActionEvent event) throws IOException {

        Parent shoppingCart_page = FXMLLoader.load(getClass().getResource("shoppingcart.fxml"));
        Scene shoppingCart_scene = new Scene(shoppingCart_page);
        Stage shoppingCart_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        shoppingCart_stage.setScene(shoppingCart_scene);
        shoppingCart_stage.show();

        System.out.println("Displaying information to console: Ensuring that user returned to main page");

    }

}

addItems.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane id="" fx:id="productPage" prefHeight="750.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="shoppingcart.addItems">
    <children>
      <GridPane layoutX="189.0" layoutY="193.0" prefHeight="364.0" prefWidth="399.0">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints maxHeight="83.0" minHeight="10.0" prefHeight="66.0" vgrow="SOMETIMES" />
          <RowConstraints maxHeight="88.0" minHeight="10.0" prefHeight="88.0" vgrow="SOMETIMES" />
          <RowConstraints maxHeight="76.0" minHeight="10.0" prefHeight="59.0" vgrow="SOMETIMES" />
            <RowConstraints maxHeight="99.0" minHeight="10.0" prefHeight="70.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
              <Text id="" fx:id="labelitemPriority" strokeType="OUTSIDE" strokeWidth="0.0" text="Item Priority:" />
              <ChoiceBox id="" fx:id="productPriority" disable="true" prefWidth="200.0" GridPane.columnIndex="1" />
              <TextField id="" fx:id="productName" prefHeight="14.0" prefWidth="63.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
              <Text id="" fx:id="labelitemName" strokeType="OUTSIDE" strokeWidth="0.0" text="Item Name:" GridPane.rowIndex="1" />
              <TextField id="" fx:id="productQty" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
              <Text id="" fx:id="labelitemQty" strokeType="OUTSIDE" strokeWidth="0.0" text="Item Qty:" GridPane.rowIndex="2" />
              <Text id="" fx:id="labelitemPrice" strokeType="OUTSIDE" strokeWidth="0.0" text="Item Price:" GridPane.rowIndex="3" />
              <TextField id="" fx:id="productPrice" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="3" />
              <Button id="itemsAdd" fx:id="productAdd" onAction="#handleitemAdd" prefHeight="37.0" prefWidth="210.0" text="ADD" GridPane.columnIndex="1" GridPane.rowIndex="4" />
         </children>
      </GridPane>
        <Text layoutX="354.0" layoutY="146.0" scaleX="4.085561690303489" scaleY="4.947136563876652" strokeType="OUTSIDE" strokeWidth="0.0" text="Add Items" wrappingWidth="67.541015625">
         <font>
            <Font size="14.0" />
         </font></Text>
        <Button id="returnCartHome" fx:id="productHome" layoutX="288.0" layoutY="609.0" mnemonicParsing="false" onAction="#handleitemReturnCart" prefHeight="48.0" prefWidth="201.0" text="Return to Cart" />
    </children>
</AnchorPane>

shoppingCartController.java

package shoppingcart;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class shoppingCartController implements Initializable {

    //Table used for Shopping Cart
    @FXML private TableView<Products> item_Table;
    @FXML private TableColumn<Products, String> item_Priority;
    @FXML private TableColumn<Products, String> item_Name;
    @FXML private TableColumn<Products, Number> item_Qty;
    @FXML private TableColumn<Products, Number> item_Price;

    private ObservableList<Products> productItems;

    //The Initializer used to load data prior to loading view.

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        item_Priority.setCellValueFactory(cellData -> cellData.getValue().itemPriorityProperty());
        item_Name.setCellValueFactory(cellData -> cellData.getValue().itemNameProperty());
        item_Qty.setCellValueFactory(cellData -> cellData.getValue().itemQtyProperty());
        item_Price.setCellValueFactory(cellData -> cellData.getValue().itemPriceProperty());

        //Display all items in table
        item_Table.setItems(getProduct());

    }

    // Method used to get the list of products
    public static ObservableList<Products> getProduct() {

    //Obseravable list which can be used to collect items
    ObservableList<Products> products = FXCollections.observableArrayList();
        return products;
    }

    public void handleitemAddition(ActionEvent event) throws IOException {

        Parent addItem_page = FXMLLoader.load(getClass().getResource("addItems.fxml"));
        Scene addItem_scene = new Scene(addItem_page);
        Stage addItem_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        addItem_stage.setScene(addItem_scene);
        addItem_stage.show();

        System.out.println("Displaying information to consoles: Deleting Selected Item");
    }
    public void handleitemDelete(ActionEvent event) throws IOException {
        System.out.println("Displaying information to consoles: Deleting Selected Item");
    }
}

shoppingcart.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane prefHeight="750.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="shoppingcart.shoppingCartController">
  <TableView fx:id="item_Table" layoutX="77.0" layoutY="174.0" prefHeight="352.0" prefWidth="646.0" tableMenuButtonVisible="true">
    <columnResizePolicy>
      <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
    </columnResizePolicy>
    <columns>
      <TableColumn fx:id="item_Priority" editable="false" prefWidth="75.0" text="Priority">
        <cellValueFactory>
          <PropertyValueFactory property="itemPriority" />
        </cellValueFactory>
      </TableColumn>
      <TableColumn fx:id="item_Name" editable="false" prefWidth="75.0" text="Item Name">
        <cellValueFactory>
          <PropertyValueFactory property="itemName" />
        </cellValueFactory>
      </TableColumn>
      <TableColumn fx:id="item_Qty" editable="false" prefWidth="75.0" text="Item Qty">
        <cellValueFactory>
          <PropertyValueFactory property="itemQty" />
        </cellValueFactory>
      </TableColumn>
      <TableColumn fx:id="item_Price" editable="false" prefWidth="75.0" text="Item Price">
        <cellValueFactory>
          <PropertyValueFactory property="itemPrice" />
        </cellValueFactory>
      </TableColumn>
    </columns>
  </TableView>
  <Text layoutX="199.0" layoutY="119.0" scaleX="1.4035087719298245" scaleY="1.7005740221599253" strokeType="OUTSIDE" strokeWidth="0.0" text="Shopping Cart Application" wrappingWidth="401.1374694108964">
    <font>
      <Font size="34.0" />
    </font>
  </Text>
  <Button id="itemsDelete" layoutX="501.0" layoutY="571.0" mnemonicParsing="false" onAction="#handleitemDelete" prefHeight="46.0" prefWidth="222.0" text="Delete Selected" />
  <Button fx:id="itemsAdd" layoutX="77.0" layoutY="571.0" onAction="#handleitemAddition" prefHeight="46.0" prefWidth="222.0" text="Add Items" />
</AnchorPane>

Edit:

I appreciate the assistance, I am still learning Java and had a follow-up question.

I updated the addItems.java to include:

public void handleitemAdd(ActionEvent event) throws IOException {

    products.add(new Products(productPriority.toString(),
            productName.getText(),
            Double.parseDouble(productPrice.getText()),
            Integer.parseInt(productQty.getText())));

    System.out.println("Displaying information to consoles: Ensuring the addItem method worked as expected.");
}

As well as the shoppingCartController to include:

public void setTableItems(ObservableList<Products> products) throws IOException {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("shoppingcart.fxml"));
    Scene shoppingCart_scene = new Scene(loader.load());
    shoppingCartController controller =  loader.getController();
    controller.setTableItems(products);
}

But the value is still not carried over, I also ensured that the parameters are being captured (confirmed with debug mode).

Freytes
  • 43
  • 10
  • @kleopatra not a problem I appreciate the advice. – Freytes Oct 01 '19 at 15:28
  • 1
    related: don't use static access (as f.i. getProduct) for anything. Plus it creates a new collection on each call, such that the items in the list are different from the items in the other form – kleopatra Oct 01 '19 at 15:32
  • @kleopatra Thanks for the comment, I didn't know that a static method creates a new collection on each call. What would you suggest implementing to resolve the issue that I am having? – Freytes Oct 01 '19 at 15:42
  • it's not the static method as such that creates a new collection, it's your implementation :) – kleopatra Oct 01 '19 at 15:53

1 Answers1

1

As @Kleopatra said in the comment static access can be tricky sometimes so be careful and stick to java common naming conventions your code is hard to trace

you can pass the item back to the ShoppingCart when returning to it by setting the list via the controller

    FXMLLoader loader = new FXMLLoader(getClass().getResource("shoppingcart.fxml"));
    Scene shoppingCart_scene = new Scene(loader.load());
    shoppingCartController controller =  loader.getController();
    controller.setProducts(list);

and in setProduct() function you can update the table
OR
You can create your ObservableList outside the static function but I don't recommend so and I suggest you search about passing data between controllers in javafx see the link below https://stackoverflow.com/a/14190310/5303683

Ahmed Emad
  • 674
  • 6
  • 19
  • I appreciate the assistance, I am still learning Java and had a follow-up question. I updated the addItems.java to include: `public void handleitemAdd(ActionEvent event) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("shoppingcart.fxml")); Scene shoppingCart_scene = new Scene(loader.load()); shoppingCartController controller = loader.getController(); controller.setTableItems(products); System.out.println("Displaying information to consoles: Ensuring the addItem method worked as expected."); }` – Freytes Oct 01 '19 at 17:28
  • And added the following to shoppingcartController but still the data is not coming through: `public void setTableItems(ObservableList products) { products.add(new Products(productPriority.toString(), productName.getText(), Double.parseDouble(productPrice.getText()), Integer.parseInt(productQty.getText()))); }` – Freytes Oct 01 '19 at 17:31
  • it's hard to follow the code in the comments could you please edit the question and add this code – Ahmed Emad Oct 01 '19 at 17:47
  • you should create and add the products list in the addItem class when the user add a new item add it to the list and when the user return to the previous stage send it back with the controller by creating a new function in the `ShoppingCartController` class called Ex. `setProducts()` that take the products list as a parameter and update the table view there feel free to ask if you have any trouble doing so – Ahmed Emad Oct 01 '19 at 17:59
  • I have attempted a few times to get the setProducts() to work. What would be the best way to update the table? – Freytes Oct 01 '19 at 18:06
  • you can update the table by setting the list that it should populate and every time the stage open it will load the list with the new added items – Ahmed Emad Oct 01 '19 at 18:19
  • and also you can `bind` the table list items to the data items that you populate from the `addItems` – Ahmed Emad Oct 01 '19 at 18:23
  • Would you mind showing me an example of how the table can be updated every time the stage is opened? I have attempted these multiple different ways through my setProducts() but it seems to not work as I expected. – Freytes Oct 01 '19 at 18:47
  • you can simply do So `public void setProducts(ObservableList products) { item_Table.setItems(products); }` – Ahmed Emad Oct 01 '19 at 18:49
  • For whatever reason it still is not populating, the variables are also binded in Products.java class. – Freytes Oct 01 '19 at 22:04
  • try to debug the variable to see if it has any values and make sure you populate the `tableview` if tableview has a problem that's another question to ask – Ahmed Emad Oct 02 '19 at 07:01
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/200307/discussion-between-freytes-and-ahmed-emad). – Freytes Oct 02 '19 at 15:21