将对象发送到javafx中的其他屏幕

时间:2016-02-23 21:25:35

标签: java javafx

我是javafx的新人,直到现在状态良好。但我找不到任何形式将对象从屏幕发送到另一个屏幕。我有点难以理解funciont od注释@FXML和来自initialize接口的方法Initializable

调用另一个

的类
public class FluxoCaixaController extends ParametrosTelas implements iTelaPrincipalFX {
    /*Atributos locais*/

    private ObservableList<String> opcoes = FXCollections.observableArrayList("Receita", "Despesa");
    private Object parent;
    private AberturaDeTelasFX formaAbertura;
    private ToggleGroup modalGroup = new ToggleGroup();
    private Categoria categoria;
    private CategoriaTreeViewController root = new CategoriaTreeViewController();


    @Override
    public void showScreen() {
        formaAbertura = new AberturaDialogFX();
        formaAbertura.loadFXML(bundle, icone, bundle.getString("screnn.fluxo.title"), new AnchorPane(), "FluxoCaixa.fxml");        
    }

    @Override // This method is called by the FXMLLoader when initialization is complete
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
        tipoField.getItems().setAll(opcoes);
        root.setParentController(getInstance());
        //idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        //descricaoColumn.setCellValueFactory(new PropertyValueFactory<>("descricao"));
        //atualizaTabela();
    }

    @FXML
    private void btnAddCetegoria() {                
        root.showScreen();
        categoriaSubcategoriaField.setText(categoria.getDescricao());
    }

    private Object getInstance(){
        return this;      

}

名为

的班级
public class CategoriaTreeViewController extends ParametrosTelas implements iTelaNormalFX {

    private AberturaDeTelasFX formaAbertura;
    private Object parent;
    private CategoriaService categoriaService = new CategoriaService();
    @FXML
    private TreeView<Categoria> treeView;
    private Categoria EmptyCategoria;
    private TreeItem<Categoria> rootItem;
    private EventHandler<MouseEvent> mouseEventHandle;

    @Override
    public void showScreen() {        
        formaAbertura = new AberturaDialogFX();
        formaAbertura.loadFXML(bundle, icone, bundle.getString("screnn.subcategory.title"), new AnchorPane(), "CategoriaTreeView.fxml");
    }

    @Override // This method is called by the FXMLLoader when initialization is complete
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
        initialiazeTree();
        mouseEventHandle = (MouseEvent event) -> {
            handleMouseClicked(event);
        };
        treeView.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEventHandle);
        treeView.setRoot(rootItem);        
    }

    private void initialiazeTree() {
        EmptyCategoria = new Categoria();
        EmptyCategoria.setDescricao("Categorias");
        rootItem = new TreeItem<>(EmptyCategoria);
        // private TreeItem<SubCategoria> itens = new TreeItem<>();
        for (Categoria g : categoriaService.listaCategorias()) {
            List<Categoria> subLst = categoriaService.listaSubCategoriasByCategoria(g.getId());
            TreeItem<Categoria> itens = new TreeItem<>(g);
            //ObservableList<Categoria> subData = FXCollections.observableArrayList(subLst);
            for (Categoria s : subLst) {
                s.setCategoria(g);
                TreeItem<Categoria> subItem = new TreeItem<>(s);
                //subItem.addEventHandler(MouseEvent, new EventHandler<MouseEvent>() {                

                itens.getChildren().add(subItem);
            }

            //itens.getChildren().add(itens);
            rootItem.getChildren().add(itens);
        }
    }

    private void handleMouseClicked(MouseEvent event) {
        if (treeView.getSelectionModel().getSelectedItem() != null) {
            Categoria name = (Categoria) ((TreeItem) treeView.getSelectionModel().getSelectedItem()).getValue();
            FluxoCaixaController fluxo = (FluxoCaixaController) getParentController();
            fluxo.setCategoria(name);
            System.out.println("Node click: " + name.getDescricao());
            formaAbertura.getStage().hide();
        }
        /*Node node = event.getPickResult().getIntersectedNode();
         // Accept clicks only on node cells, and not on empty spaces of the TreeView
         if (node instanceof Text || (node instanceof TreeCell && ((TreeCell) node).getText() != null)) {
         String name = (String) ((TreeItem)treeView.getSelectionModel().getSelectedItem()).getValue();
         System.out.println("Node click: " + name);
         }*/
    }


}

接口必须指向或两个方法。 AberturaDeTelasFX界面有一个实现,说明屏幕应该如何打开。

AberturaNormalFX

public class AberturaNormalFX implements AberturaDeTelasFX {

    private Stage stage;

    @Override
    public void loadFXML(ResourceBundle bundle, Image icon, String title, Node node, String fxmlPath) {
        try {
            // Carrega o root layout do arquivo fxml.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass()
                    .getResource(fxmlPath));
            loader.setResources(bundle);
            if (node instanceof BorderPane) {
                BorderPane rootLayout = (BorderPane) loader.load();
                showLayout(icon, title, rootLayout);
            } else if (node instanceof AnchorPane) {
                AnchorPane rootLayout = (AnchorPane) loader.load();
                showLayout(icon, title, rootLayout);
            }

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

    private void showLayout(Image icone, String title, Parent node) {
        stage = new Stage();
        Scene scene = new Scene(node);
        stage.setTitle(title);
        stage.getIcons().add(icone);
        stage.setScene(scene);

        stage.show();
    }

    @Override
    public void loadFXML(String title, Node node, String fxmlPath) {
        throw new UnsupportedOperationException("Not supported yet."); //To chan

生成方法的ge体,选择工具|模板。     }

/**
 * @return the stage
 */
@Override
public Stage getStage() {
    return stage;
}

}

1 个答案:

答案 0 :(得分:0)

查看您的代码我找不到一个扩展Application的类。 在我最近构建的项目中,我将它用作Presentation层的一部分,它是控制器(代表Controller层)之间的桥梁,每个控制器管理一个屏幕。请考虑以下示例:

public class MainAppFX extends Application {

// The primary window or frame of this application
private Stage primaryStage;

这个病人&#39;表示来自控制器的对象:

private PatientData patient; 

/**
 * Default constructor
 */
public MainAppFX() {
    super();
}

/**
 * The application starts here
 *
 * @param primaryStage
 * @throws Exception
 */
@Override
public void start(Stage primaryStage) throws Exception {

    log.info("Program loads");

    // The Stage comes from the framework so make a copy to use elsewhere
    this.primaryStage = primaryStage;
    // Create the Scene and put it on the Stage
    loadPatientParentWindow();

    // Set the window title
    this.primaryStage.setTitle("Your Window title");

    this.primaryStage.show();
}

/**
 * Loads Patient FXML layout
 * This method loads one of your screens
 */
public void loadPatientParentWindow() {

    try {

        // Instantiate the FXMLLoader
        FXMLLoader loader = new FXMLLoader();
        // Set the location of the fxml file in the FXMLLoader
    loader.setLocation(MainAppFX.class.getResource("/fxml/PatientForm.fxml"));

        // Parent is the base class for all nodes that have children in the
        // scene graph such as AnchorPane and most other containers
        Parent parent = (AnchorPane) loader.load();

        // Load the parent into a Scene
        Scene scene = new Scene(parent);

        // Put the Scene on Stage
        primaryStage.setScene(scene);

        // Give the PatientFXMLController controller access to the main app.
        PatientFXMLController controller = loader.getController();

下面是Patient控制器的setter方法,它可以访问Main类

        controller.setMainAppFX(this); 

    } catch (IOException | SQLException ex) { // getting resources or files could fail
        log.error(null, ex);
        System.exit(1);
    }
}


/**
 * Setter for PatientData object in the Main class

你在控制器类中使用它

 *
 * @param patient
 */
public void setPatient(PatientData patient) {
    this.patient = patient;
}

/**
 * Getting PatientData object from the Main class
 *
 * @return
 */
public PatientData getPatient() {
    return patient;
}

/**
 * Where it all begins
 *
 * @param args command line arguments
 */
public static void main(String[] args) {
    launch(args);
    System.exit(0);
}

}

这是控制器类之一,代表其中一个屏幕:

public class PatientFXMLController {

主要应用程序的引用从这里开始

private MainAppFX mainApp;

您将使用setter

传递给主类的下一个对象
private PatientData patient;

// The @FXML annotation on a class variable results in the matching
// reference being injected into the variable
// label is defined in the fxml file
// Bunch of @FXML annotations with respective fields (you can get them from SceneBuilder)
@FXML
private TextField patientIdField;
@FXML
private TextField lastNameField;
// so on...


/**
 * The constructor. The constructor is called before the initialize()
 * method. You don't need to call it. It's being called by automatically
 */
public PatientFXMLController() {
    super();

为初始化方法

创建空的Patient对象
    patient = new PatientData();
}

/**
 * Initializes the controller class. This method is automatically called
 * after the fxml file has been loaded. Useful if a control must be
 * dynamically configured such as loading data into a table.
 */
@FXML
private void initialize() {
    log.info("initialize called");

    // Initializing form fields
    Bindings.bindBidirectional(patientIdField.textProperty(), patient.patientIdProperty(), new NumberStringConverter());
    // so on .....
}

/**
 * Loads Another screen

下面的方法表示按钮的操作,该按钮指向另一个屏幕,并将对象从此控制器传递到主类。然后你可以将这个对象从main类传递给anotherScreen控制器,因为你将在那里有loadAnotherScreenWindow()方法

 *
 * @param event
 */
@FXML
private void loadAnotherScreen(ActionEvent event) throws SQLException {

将Patient对象传递给主类,以便可以在另一个屏幕控制器中使用以获取相关的住院患者

    mainApp.setPatient(patient);
}


/**
 * Is called by the main application to give a reference back to itself.
 * This class receives the reference of the main class.
 *
 * @param mainApp
 */
public void setMainAppFX(MainAppFX mainApp) {
    this.mainApp = mainApp;
}

/**
 * Setter for PatientData object
 *
 * @param patient
 */
public void setPatient(PatientData patient) {
    this.patient = patient;
}

}