在JavaFX中打开新窗口时如何运行默认代码(初始化)

问题描述 投票:1回答:1

当我从JavaFX的主控制器中打开NewWindow时,我想要一种运行一些代码的方法。

这是我的主控制器有:

public class FXMLDocumentController implements Initializable {
//consider all variables and or elements initialized
final Stage newWindow = new Stage();

@FXML
private void searchButtonAction(ActionEvent event)  {
    //Clicking on Search button triggers this event handler and Search Window will open with all the results
    newWindow.show();
}

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

    try {
        newWindow.initModality(Modality.APPLICATION_MODAL);
        //Loader to load the Search Window
        FXMLLoader loader = new FXMLLoader(
                getClass().getResource("SearchWindow.fxml")
        );
        Scene scene = new Scene(loader.load());
        newWindow.setScene(scene);
        SearchWindowController controller = loader.<SearchWindowController>getController();
        controller.mainWindow = this;

    } catch (Exception e) {
        System.err.println(e.getMessage());
    }`
}`}`

这是我的新窗口控制器:

public class SearchWindowController implements Initializable {

@FXML
void searchButtonAction() {
    //Code i want to run when this window opens
    } catch (Exception e) {
        System.err.print(e);
    }
}

/**
 * Initializes the controller class.
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    //empty 
    //call searchButtonAction() when this window opens ??? 
}

所以基本上会打开新窗口,但是我想运行一些我在加载时拥有的代码。我经历了一些地方,并注意到我可以创建一个start方法,该方法应该在新窗口启动时运行。但是我无法使其在我的代码中运行。我看到的另一种方法是放置事件处理程序。

我的问题再次是我是否要实现上述方法,我应该将这些方法/事件处理程序确切地放在哪里。我希望在窗口加载时默认调用我的searchButtonAction()。另一种方法也将有所帮助。一些例子将不胜感激。

编辑:我希望输出显示在newWindow上,其基本上是一些文本,这些文本是从主窗口中提取并在新窗口中显示的。 (当前我的解决方法是在新窗口中创建一个新按钮,然后在该按钮上放置onClickAction事件以运行searchButtonAction())。我希望searchButtonAction()默认运行。如何初始化它,以便在打开新窗口时调用searchButtonAction()。

谢谢你。

javafx fxml
1个回答
0
投票

我有这个问题。我在fxml文件中指定了错误的控制器。当我为fxml文件指定了正确的控制器时,它就起作用了。

© www.soinside.com 2019 - 2024. All rights reserved.