Добавление параметров к вызову класса не позволяет открывать новый метод окна. Java FX - PullRequest
0 голосов
/ 17 марта 2020

При передаче параметров через вызов нового класса из контроллера, кажется, что существование параметров не позволяет классу правильно выполнить свой метод открытия нового окна (метод, который существует в вызываемом классе, который открывает новое окно). Однако при повторном создании примеров данных внутри класса в методе initialize и без прохождения через параметры вызов класса и его нового метода создания окна работает нормально.

Построение методов таблиц / графиков et c вызывается в методе инициализации нового класса. Создание нового окна - это метод, который вызывается внутри контроллера после инициализации самого класса.

Любая помощь приветствуется. Спасибо.

Main:
package sample;

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("sample.fxml"));
        primaryStage.setTitle("Example"); //set the name of the title
        primaryStage.setScene(new Scene(root, 1200, 750)); //width and height of pane
        primaryStage.sizeToScene();
        primaryStage.show();
        primaryStage.setMinWidth(primaryStage.getWidth());
        primaryStage.setMinHeight(primaryStage.getHeight());
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Controller:package sample;

import java.util.ArrayList;
import java.util.Random;
import java.util.Set;

public class Controller {

    public Controller() {
    }
    public void openWin() {
//         Example Data Set
        ArrayList<ArrayList<Double>> data = new ArrayList<>();
        for (double j = 0; j < 5; j++) {
            ArrayList<Double> exampleDataSet = new ArrayList<>();
            exampleDataSet.add(j);
            for (int i = 0; i < 5; i++) {
                Random r = new Random();
                double randomValue = 0 + (100 - 0) * r.nextDouble();
                exampleDataSet.add(randomValue);
            }
            data.add(exampleDataSet);
        }
        //Example Headers for Data Set
        String headers = "Header1, Header2, Header3, Header4, Header5";
        //Open New Window (this is upon button click)
        Win newWin = new Win(headers, data);
        newWin.openNewWin();
    }

//
//

}

Win Class:package sample;

import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.ArrayList;
import java.util.List;

public class Win {
    @FXML private TableView<ObservableList<Double>> tableView = new TableView<>();

    private Stage stage = new Stage();

    String headers[] = null;
    String items[] = null;
    List<String> columns = new ArrayList<String>();
    List<String> rows = new ArrayList<String>();
    ObservableList<ObservableList<Double>> csvData = FXCollections.observableArrayList();

    private String newHeaders;
    private ArrayList<ArrayList<Double>> data = new ArrayList<>();

    public Win(String headers, ArrayList data) {
        this.newHeaders = headers;
        this.data = data;
    }
    public void initialize() {
        generateTable(newHeaders, data);
    }

    public void openNewWin() {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("win.fxml"));
            Parent root1 = fxmlLoader.load();
            stage.initStyle(StageStyle.DECORATED);
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.setTitle("Table");

            stage.setScene(new Scene(root1));
            stage.show();

        } catch(Exception e) {
            System.out.println("Cannot load new window");
            System.err.println(e.getMessage());
            System.out.println(newHeaders);
            System.out.println(data);
        }
    }
    public void generateTable(String newHeaders, ArrayList<ArrayList<Double>> dataset) {
        try {
            System.out.println(newHeaders);
            System.out.println(dataset);
            headers = newHeaders.split(",");
            for (String w : headers) {
                columns.add(w);
            }

            for (int i = 0; i < columns.size(); i++) {
                final int finalIdx = i;
                TableColumn<ObservableList<Double>, Double> column = new TableColumn<>(columns.get(i));
                column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx))); //Set text
                tableView.getColumns().add(column);
            }

            for (ArrayList<Double> array : dataset) {
                ObservableList<Double> row = FXCollections.observableArrayList();
                row.clear();
                for (double number : array) {
                    row.add(number);
                }
                csvData.add(row);
            }
            tableView.setItems(csvData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>

<?import javafx.scene.layout.*?>

<GridPane id="gridPane" alignment="top_center" gridLinesVisible="false" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller"> <!--will show gaps between columns, rows & cells-->
    <!-- can use center -->
    <!--forcing width of columns-->
    <padding>
        <Insets bottom="10" left="30" right="30" top="10" /> <!-- will have a gap between title and below-->
    </padding>

    <Button onAction="#openWin" GridPane.rowIndex="0" GridPane.columnIndex="10" text="Exit"/>
</GridPane>

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

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<GridPane id="gridPane" alignment="top_center" gridLinesVisible="false" hgap="10" prefHeight="650.0" prefWidth="1000.0" vgap="10" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Win">
    <TableView fx:id="tableView"  GridPane.columnIndex="0" GridPane.columnSpan="3" GridPane.rowIndex="3" />

</GridPane>


<!--The Grid Pane for win would include other items like buttons and graphs-->

...