2016-04-25 88 views
0

我正在使用JavaFX并在一个Schoolproject上工作。如何处理另一个类的ActionEvent

关于我的程序,我有一个登录屏幕,如果我按登录,我来到大型机。大型机的内容区域是空的,因为当我使用菜单栏中的按钮时,我加载了构建大型机的AnchorPane的内容。

当我按下登录按钮时,我想放置大框架和主窗格。但我不知道如何将窗格从另一个类加载到大型机中。

这里我的代码:

代码加载主机:

@FXML 
protected void login(ActionEvent event) throws IOException, URISyntaxException { 
    Stage stage; 
    Parent root = null; 
    stage = (Stage) btnLogin.getScene().getWindow(); 
    try{ 
     root = FXMLLoader.load(getClass().getResource("view/mainframe.fxml")); 
     } catch (IOException e){ 
      e.printStackTrace(); 
     } 
    Scene scene = new Scene(root, 1280, 900); 
    stage.setScene(scene); 
    stage.show();  

} 

守则LAOD家窗格到主机:

@FXML 
protected void mHome(ActionEvent event) throws IOException, URISyntaxException { 

    try {      
     URL url = getClass().getResource("view/home.fxml"); 
     FXMLLoader fxmlLoader = new FXMLLoader(); 
     fxmlLoader.setLocation(url); 
     fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); 
     AnchorPane page = (AnchorPane) fxmlLoader.load(url.openStream()); 

     aContent.getChildren().clear(); 
     aContent.getChildren().add(page); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

这两种方法在不同的班级。

如果您需要了解更多信息,请让我知道:)

谢谢你,映入眼帘,蒂莫

回答

0

只需调用mHome()方法。请注意,由于您从不使用ActionEvent,因此您可以从方法签名中省略它(FXMLLoader仍然可以将其映射为事件处理程序)。因此,将其更改为

@FXML 
protected void mHome() throws IOException, URISyntaxException { 

    try {      
     URL url = getClass().getResource("view/home.fxml"); 
     FXMLLoader fxmlLoader = new FXMLLoader(); 
     fxmlLoader.setLocation(url); 
     fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); 
     AnchorPane page = (AnchorPane) fxmlLoader.load(url.openStream()); 

     aContent.getChildren().clear(); 
     aContent.getChildren().add(page); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

如果总是要显示的“家窗格”时,首先显示的主面板中,只是为了mHome添加调用initialize()方法在同一个控制器类:

public void initialize() { 
    // existing code... 

    mHome(); 
} 

或者,如果你特别只想显示“家窗格”当你从登录面板中加载它,在你登录处理程序的调用添加到mHome

@FXML 
protected void login(ActionEvent event) throws IOException, URISyntaxException { 
    Stage stage; 
    Parent root = null; 
    stage = (Stage) btnLogin.getScene().getWindow(); 
    try{ 
     FXMLLoader loader = new FXMLLoader(getClass().getResource("view/mainframe.fxml")); 
     root = loader.load(); 
     MainController controller = loader.getController(); 
     controller.mHome(); 
    } catch (Exception e){ 
     e.printStackTrace(); 
    } 
    Scene scene = new Scene(root, 1280, 900); 
    stage.setScene(scene); 
    stage.show();  

} 

(我假设MainControllermainframe.fxml控制器类的名称;显然只是根据需要调整。)

+0

好吧,我试过了,它的工作原理。现在的问题是,我已经实现了这个代码: 'aContent.getChildren()。clear(); aContent.getChildren()。add(page);' 在我将新的fxml添加到窗格之前,清除AnchorPane aContent。但现在它是空的,所以它不能清除它,并给我一个错误... – TeemoBiceps