无法在javafx

时间:2016-07-05 10:23:07

标签: intellij-idea javafx tableview

我正在使用intelliJ构建一个简单的Inventory程序,我正在尝试从统计控制器(OnFloorStatsController)访问从一个控制器(MaterialOverviewController)加载的表。

我有一个RootLayoutController,我设法获取打印用途,但我似乎无法从OnFloorStatsController做同样的事情。)

以下是我的RootLayoutController中的代码:

@FXML
private void handlePrint() {

    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("MaterialOverview.fxml"));
    try {
        AnchorPane frame = fxmlLoader.load();
    } catch (IOException e) {
        e.printStackTrace();
    }
    MaterialOverviewController c = fxmlLoader.getController();

    //Loads data into table
    c.setMainApp(mainApp);
PrinterJob printerJob = PrinterJob.createPrinterJob();

if (printerJob != null) {
            boolean showDialog = printerJob.showPrintDialog(mainApp.getPrimaryStage().getOwner());
if (showDialog) {
                c.getMaterialTable().setScaleX(0.72);
                c.getMaterialTable().setScaleY(1.0);
                c.getMaterialTable().setTranslateX(-94);
                c.getMaterialTable().setTranslateY(-0);
                boolean success = printerJob.printPage(c.getMaterialTable());
                if (success) {
                    printerJob.endJob();
                }
                c.getMaterialTable().setTranslateX(0);
                c.getMaterialTable().setTranslateY(0);
                c.getMaterialTable().setScaleX(1.0);
                c.getMaterialTable().setScaleY(1.0);
            }
        }

当我尝试使用时:

FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("MaterialOverview.fxml"));
    try {
        AnchorPane frame = fxmlLoader.load();
    } catch (IOException e) {
        e.printStackTrace();
    }
    MaterialOverviewController c = fxmlLoader.getController();

    //Loads data into table
    c.setMainApp(mainApp);

进入我的OnFloorStatsController,我在c.setMainApp(mainApp)上得到一个空指针异常;

我觉得自己不能解决这个问题

编辑:

以下是我想要访问的控制器代码:

    package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;

import java.util.Arrays;
import java.util.List;

public class MaterialOverviewController {
    @FXML
    private TableView<Material> materialTable;
    @FXML
    private TableColumn<Material, String> pONumberColumn;
    @FXML
    private TableColumn<Material, String> materialNameColumn;
    @FXML
    private TableColumn<Material, String> materialIdColumn;
    @FXML
    private TableColumn<Material, Double> materialWidthColumn;
    @FXML
    private TableColumn<Material, Integer> qtyOrderedColumn;
    @FXML
    private TableColumn<Material, Integer> qtyReceivedColumn;
    @FXML
    private TableColumn<Material, Integer> qtyBackOrderedColumn;
    @FXML
    private TableColumn<Material, Integer> qtyOnFloorColumn;
//    @FXML
//    private TableColumn<Material, DatePicker> dateOrderedColumn;
//    @FXML
//    private TableColumn<Material, DatePicker> estArrivalColumn;
    @FXML
    private TableColumn<Material, String> dateOrderedColumn;
    @FXML
    private TableColumn<Material, String> estArrivalColumn;
    @FXML
    private TableColumn<Material, String> supplierColumn;


    @FXML
    private TextField pONumberLabel;
    @FXML
    private TextField materialIdLabel;
    @FXML
    private TextField materialNameLabel;
    @FXML
    private TextField materialWidthLabel;
    @FXML
    private TextField qtyOrderedLabel;
    @FXML
    private TextField qtyRecievedLabel;
    @FXML
    private TextField qtyBackOrderedLabel;
    @FXML
    private TextField estArrivalLabel;
    @FXML
    private TextField qtyOnFloorLabel;
    @FXML
    private TextField supplierLabel;
    @FXML
    private TextField dateOrderedLabel;
    @FXML
    private TextField totalTextField;
    @FXML
    private TextField materialTextField;
    private int materialTotal;
    private String materialName;

    private List<Material> materialId;

    public TableView<Material> getMaterialTable() {
        return materialTable;
    }

//    public void setMaterialTable(TableView<Material> materialTable) {
//        this.materialTable = materialTable;
//    }

    private ObservableList<Integer> rollsTotal = FXCollections.observableArrayList();
    private ObservableList<String> materialNames = FXCollections.observableArrayList();



    // Reference to the main application.
    private MainApp mainApp;

    public MainApp getMainApp() {
        return mainApp;
    }

    /**
     * The constructor.
     * The constructor is called before the initialize() method.
     */
    public MaterialOverviewController() {
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        materialTotal = 0;
        // Initialize the material table with columns.
        pONumberColumn.setCellValueFactory(cellData -> cellData.getValue().pONumberProperty());
        materialNameColumn.setCellValueFactory(cellData -> cellData.getValue().materialNameProperty());
        materialIdColumn.setCellValueFactory(cellData -> cellData.getValue().materialIdProperty());
        materialWidthColumn.setCellValueFactory(cellData -> cellData.getValue().materialWidthProperty().asObject());
        qtyOrderedColumn.setCellValueFactory(cellData -> cellData.getValue().qtyOrderedProperty().asObject());
        qtyReceivedColumn.setCellValueFactory(cellData -> cellData.getValue().qtyReceivedProperty().asObject());
        qtyBackOrderedColumn.setCellValueFactory(cellData -> cellData.getValue().qtyBackOrderedProperty().asObject());
//        qtyBackOrderedColumn.setCellValueFactory(cellData -> cellData.getValue().qtyBackOrderedProperty().asObject());
        qtyOnFloorColumn.setCellValueFactory(cellData -> cellData.getValue().qtyOnFloorProperty().asObject());
//        dateOrderedColumn.setCellValueFactory(cellData -> cellData.getValue().dateOrderedProperty().asString());
        dateOrderedColumn.setCellValueFactory(cellData -> cellData.getValue().dateOrderedProperty().asString());
        estArrivalColumn.setCellValueFactory(cellData -> cellData.getValue().dateExpectedProperty().asString());
        supplierColumn.setCellValueFactory(cellData -> cellData.getValue().supplierProperty());

        // Clear material details.
        showMaterialDetails(null);

        // Listen for selection changes and show the material details when changed.
        materialTable.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> showMaterialDetails(newValue));

    }

    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;

        // Add observable list data to the table
        materialTable.setItems(mainApp.getMaterialData());
    }

    private void showMaterialDetails(Material material) {
        if (material != null) {
            // Fill the labels with info from the material object.
            pONumberLabel.setText(material.getPoNumber());
            materialIdLabel.setText(material.getMaterialId());
            materialNameLabel.setText(material.getMaterialName());
            materialWidthLabel.setText(String.valueOf(material.getMaterialWidth()));
            qtyOrderedLabel.setText(Integer.toString(material.getQtyOrdered()));
            qtyRecievedLabel.setText(Integer.toString(material.getQtyReceived()));
            qtyBackOrderedLabel.setText(Integer.toString(material.getQtyOrdered()-material.getQtyReceived()));
//            qtyBackOrderedLabel.setText(Integer.toString(material.getQtyBackOrdered()));
            qtyOnFloorLabel.setText(Integer.toString(material.getQtyOnFloor()));
//            dateOrderedLabel.setText(DateUtil.format(material.getDateOrdered()));
//            dateOrderedLabel.equals(DateUtil.format(material.getDateOrdered()));
//            dateOrderedLabel.setText(DatePicker(String.valueOf(material.getDateOrdered());
//            estArrivalLabel.setText(material.getSupplier());
            supplierLabel.setText(material.getSupplier());

            String pattern = "MM/dd/yyyy";
//            dateTestTextField.setText(DateUtil.format(material.getBirthday()));
            dateOrderedLabel.setText(DateUtil.format(material.getDateOrdered()));
            estArrivalLabel.setText(DateUtil.format(material.getDateExpected()));
            //TODO: set running material totals
//            getMaterialNames(Arrays.asList(material));
            handleSelectMaterial();

        } else {
            // Material is null, remove all the text.
            pONumberLabel.setText("");
            materialIdLabel.setText("");
            materialNameLabel.setText("");
            materialWidthLabel.setText("");
            qtyOrderedLabel.setText("");
            qtyRecievedLabel.setText("");
            qtyBackOrderedLabel.setText("");
            qtyOnFloorLabel.setText("");
            dateOrderedLabel.setText("");
            estArrivalLabel.setText("");
            supplierLabel.setText("");
//            dateOrderedLabel.setText("");


//            dateOrderedLabel.setConverter();
//            estArrivalLabel.setText("");
//            dateOrderedLabel.setText("");
        }
    }

    @FXML
    private void handleDeleteMaterial() {
//        int selectedIndex = materialTable.getSelectionModel().getSelectedIndex();
//        materialTable.getItems().remove(selectedIndex);
        int selectedIndex = materialTable.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0) {
            materialTable.getItems().remove(selectedIndex);
        } else {
            // Nothing selected.
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.initOwner(mainApp.getPrimaryStage());
            alert.setTitle("No Selection");
            alert.setHeaderText("No Material Selected");
            alert.setContentText("Please select an order in the table.");

            alert.showAndWait();
        }
    }

    @FXML
    private void handleNewMaterial() {
        Material tempMaterial = new Material();
        boolean okClicked = mainApp.showMaterialEditDialog(tempMaterial);
        if (okClicked) {
            mainApp.getMaterialData().add(tempMaterial);
        }
    }

    @FXML
    private void handleEditMaterial() {
        Material selectedMaterial = materialTable.getSelectionModel().getSelectedItem();
        if (selectedMaterial != null) {
            boolean okClicked = mainApp.showMaterialEditDialog(selectedMaterial);
            if (okClicked) {
                showMaterialDetails(selectedMaterial);
            }

        } else {
            // Nothing selected.
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.initOwner(mainApp.getPrimaryStage());
            alert.setTitle("No Selection");
            alert.setHeaderText("No Material Selected");
            alert.setContentText("Please select a material in the table.");

            alert.showAndWait();
        }
    }

//    public List<Material> getMaterialIds() {
//        for (Material id : materialId)
//        return Arrays.asList(id.getMaterialId());
//    }

    public void setMaterialTotal(List<Material> materials) {
        // Count the number of people having their birthday in a specific month.
//        int[] monthCounter = new int[12];
        Material[] matId = new Material[20];
        for (Material m : materials) {
            Integer id = Integer.parseInt(m.getMaterialId());
//            qty = m.getQtyBackOrdered();
//            monthCounter[qty]++;
            materialId.add(matId[id]);
        }
        for (Material id : materialId)
            materialTextField.setText(String.valueOf(id)+"%n");
    }

    public Integer getTotals () {
        return null;
    }


    public List getMaterialNames(List<Material> materials) {

        for (Material name : materials) {
            mainApp.getMaterialData();
            if (!materialNames.contains(name)) {
                materialNames.add(name.getMaterialName());
            }
        }
        for (String name : materialNames) {
            materialTextField.setText(name + "\n");
        }
        return Arrays.asList(materialNames);
    }

    @FXML
    private void handleSelectMaterial() {
        Material selectedMaterial = materialTable.getSelectionModel().getSelectedItem();
        if (selectedMaterial != null) {
            materialTotal = 0;
            String stockId = selectedMaterial.getMaterialId();
            materialName = selectedMaterial.getMaterialName();
            Double width = selectedMaterial.getMaterialWidth();
            materialTextField.setText(materialName + ", " + String.valueOf(width) + " inches");
            for (Material id : mainApp.getMaterialData()) {
                if (id.getMaterialWidth() == width && id.getMaterialId().equalsIgnoreCase(stockId)) {
                    materialTotal += id.getQtyOnFloor();
                }
                    totalTextField.setText(String.valueOf(materialTotal));
            }
        }
    }

}

以下是想要访问的控制器:

    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.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

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

public class OnFloorStatsController {

//    @FXML
//    private TableView<Material> materialTable;

    @FXML
    private BarChart<String, Integer> bc;

    @FXML
    private CategoryAxis xAxis = new CategoryAxis();

    @FXML
    private NumberAxis yAxis = new NumberAxis();

    @FXML
    private MaterialOverviewController getMvc;


    private ObservableList<String> materialIds = FXCollections.observableArrayList();
    private ObservableList<Material> materialz = FXCollections.observableArrayList();


    private MainApp mainApp;
    private MaterialOverviewController mMaterialOverviewController;
    public TableView<Material> material;

    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }



//    final static String austria = "14532";
//    final static String brazil = "78333";
//    final static String france = "40443";
//    final static String italy = "72825";
//    final static String usa = "72829";

    public void getData() {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("MaterialOverview.fxml"));
        try {
            AnchorPane frame = fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MaterialOverviewController c = fxmlLoader.getController();

        //Loads data into table
        c.setMainApp(mainApp);
    }


    public void start(Stage stage) {

        getData();
        stage.setTitle("Material On Floor");
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        final BarChart<String, Number> bc =
                new BarChart<String, Number>(xAxis, yAxis);
        bc.setTitle("Material On Floor");
        xAxis.setLabel("Material");
        yAxis.setLabel("Quantity");


        XYChart.Series series1 = new XYChart.Series();
        series1.setName("6 inch");
        Integer floorTotal = 0;


        for (Material id :mainApp.getMaterialData()) {
            if (id.getMaterialWidth() < 6.9) {
                floorTotal = id.getQtyOnFloor();
                for (Material size : mainApp.getMaterialData()) {
                    if ( id.getMaterialId().equalsIgnoreCase(size.getMaterialId()) &&
                            size.getMaterialWidth() == id.getMaterialWidth()) {
                        floorTotal += size.getQtyOnFloor();
                    }
                    else {
                        floorTotal = id.getQtyOnFloor();
                    }
//        for (Material id : mainApp.getMaterialData()) {
//            if (id.getMaterialWidth() < 7) {
                }
            }
//            else {
//                series1.getData().add(new XYChart.Data(id.getMaterialId(), 0));
//            }
                series1.getData().add(new XYChart.Data(id.getMaterialId(), floorTotal));
        }
//                series1.getData().add(new XYChart.Data(austria, 10));
//        series1.getData().add(new XYChart.Data(brazil, 1));
//        series1.getData().add(new XYChart.Data(france, 10));
//        series1.getData().add(new XYChart.Data(italy, 7));
//        series1.getData().add(new XYChart.Data(usa, 3));

//        XYChart.Series series2 = new XYChart.Series();
//        series2.setName("8 inch");
////        for (Material id : mainApp.getMaterialData()) {
//        for (Material id : materialz) {
////            if (id.getMaterialWidth() > 6.9 ) {
//                series2.getData().add(new XYChart.Data(id.getMaterialId(), id.getQtyOnFloor()));
////            }
////            else {
////                series2.getData().add(new XYChart.Data(id.getMaterialId(), 0));
////            }
//        }
//        series2.getData().add(new XYChart.Data(austria, 3));
//        series2.getData().add(new XYChart.Data(brazil, 7));
//        series2.getData().add(new XYChart.Data(france, 7));
//        series2.getData().add(new XYChart.Data(italy, 10));
//        series2.getData().add(new XYChart.Data(usa, 5));

//        XYChart.Series series3 = new XYChart.Series();
//        series3.setName("Other");
//        for (Material id : materialz) {
//            if (id.getMaterialWidth() < 5.9 || id.getMaterialWidth() > 9.1) {
//                series3.getData().add(new XYChart.Data(id.getMaterialId(), id.getQtyOnFloor()));





        Scene scene = new Scene(bc, 800, 600);
        bc.getData().addAll(series1/*, series2, series3*/);
        stage.setScene(scene);
        stage.show();
    }


}

这是调用OnFloorStatsController的控制器:

package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventDispatchChain;
import javafx.event.EventDispatcher;
import javafx.fxml.FXMLLoader;
import javafx.print.*;
import javafx.scene.Node;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
import sample.MaterialOverviewController;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

import com.sun.java.swing.action.CancelAction;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.stage.FileChooser;
import javafx.scene.control.TableView;

/**
 *
 * The controller for the root layout. The root layout provides the basic
 * application layout containing a menu bar and space where other JavaFX
 * elements can be placed.
 *
 */
public class RootLayoutController {

    // Reference to the main application
    private MainApp mainApp;
    private MaterialOverviewController mMaterialOverviewController;
    public TableView<Material> material;


    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }

    /**
     * Creates an empty material inventory.
     */
    @FXML
    private void handleNew() {
        mainApp.getMaterialData().clear();
        mainApp.setMaterialFilePath(null);
    }

    /**
     * Opens a FileChooser to let the user select an address book to load.
     */
    @FXML
    private void handleOpen() {
        FileChooser fileChooser = new FileChooser();

        // Set extension filter
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
                "XML files (*.xml)", "*.xml");
        fileChooser.getExtensionFilters().add(extFilter);

        // Show save file dialog
        File file = fileChooser.showOpenDialog(mainApp.getPrimaryStage());

        if (file != null) {
            mainApp.loadMaterialDataFromFile(file);
        }
    }

    /**
     * Saves the file to the person file that is currently open. If there is no
     * open file, the "save as" dialog is shown.
     */
    @FXML
    private void handleSave() {
        File materialFile = mainApp.getMaterialFilePath();
        if (materialFile != null) {
            mainApp.saveMaterialDataToFile(materialFile);
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setHeaderText("File Saved");
            alert.showAndWait();
        } else {
            handleSaveAs();
        }
    }

    /**
     * Opens a FileChooser to let the user select a file to save to.
     */
    @FXML
    private void handleSaveAs() {
        FileChooser fileChooser = new FileChooser();

        // Set extension filter
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
                "XML files (*.xml)", "*.xml");
        fileChooser.getExtensionFilters().add(extFilter);

        // Show save file dialog
        File file = fileChooser.showSaveDialog(mainApp.getPrimaryStage());

        if (file != null) {
            // Make sure it has the correct extension
            if (!file.getPath().endsWith(".xml")) {
                file = new File(file.getPath() + ".xml");
            }
            mainApp.saveMaterialDataToFile(file);
        }
    }

    /**
     * Opens an about dialog.
     */
    @FXML
    private void handleAbout() {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Material Inventory");
        alert.setHeaderText("About");
        alert.setContentText("Version 1.2\n\nCreator: Mike Brisson\n\nMark can't say I've never given him anything :)");

        alert.showAndWait();
    }

    @FXML
    private void handleEdit() {
        Alert alert = new Alert(AlertType.WARNING);
        alert.setTitle("Why would you click that?");
        alert.setHeaderText("You can't follow instructions very well");
        alert.setContentText("Was it worth it?");

        alert.showAndWait();
    }

    @FXML
    private void handlePrint() {

        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("MaterialOverview.fxml"));
        try {
            AnchorPane frame = fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MaterialOverviewController c = fxmlLoader.getController();

        //Loads data into table
        c.setMainApp(mainApp);

        PrinterJob printerJob = PrinterJob.createPrinterJob();

//        if(printerJob.showPrintDialog(mainApp.getPrimaryStage().getOwner()) && printerJob.printPage(c.getMaterialTable()))
//            printerJob.endJob();

        if (printerJob != null) {
            boolean showDialog = printerJob.showPrintDialog(mainApp.getPrimaryStage().getOwner());
//            boolean showDialog = printerJob.showPageSetupDialog(mainApp.getPrimaryStage().getOwner());
            if (showDialog) {
                c.getMaterialTable().setScaleX(0.72);
                c.getMaterialTable().setScaleY(1.0);
                c.getMaterialTable().setTranslateX(-94);
                c.getMaterialTable().setTranslateY(-0);
                boolean success = printerJob.printPage(c.getMaterialTable());
                if (success) {
                    printerJob.endJob();
                    showDialog=false;
                }
                c.getMaterialTable().setTranslateX(0);
                c.getMaterialTable().setTranslateY(0);
                c.getMaterialTable().setScaleX(1.0);
                c.getMaterialTable().setScaleY(1.0);
            }
            showDialog=false;
        }

    }


    @FXML
    private void handleShowMaterialStatistics() {

        mainApp.showMaterialStatistics();
    }

    @FXML
    private void handleShowOnFloorStats() {
        mainApp.showOnFloorStatistics();
    }

    @FXML
    private void handleShowBarChartTest() {
        mainApp.showBarChartTest();
    }

    /**
     * Closes the application.
     */
    @FXML
    private void handleExit() {
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Exit Confirmation");
        alert.setHeaderText("Are you sure you want to exit without Saving?");
        alert.setContentText("Choose your option.");

        ButtonType buttonSave = new ButtonType("Save");
        ButtonType buttonCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
        ButtonType buttonExit = new ButtonType("Exit");

        alert.getButtonTypes().setAll(buttonSave, buttonCancel, buttonExit);

        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == buttonSave){
            handleSaveAs();
        } else if (result.get() == buttonExit) {
            System.exit(0);

        } else if (result.get() == buttonCancel){
            alert.close();
        }

    }
}

0 个答案:

没有答案