简体   繁体   中英

Updating UI Components of One Stage Based On Event in Another Stage in JavaFX

I have two Stages , for instance, Stage1 and Stage2. Stage1 has a ListView and a Button . OnPressing button present on Stage1, I open a dialog ie Stage2. Stage2 has TextField and a Button . If I enter a string in TextField and click on the button, I close the previous Stage1. Now, I want to update the ListView once I click on stage2 button.

I don't close Stage1 when I press button to open the dialog.

I use showAndWait function on stage2

window.showAndWait();

and close it using

stage.close();

Above is a part of the stage. There are other components which I would like to refresh based on the button press in stage2.

Could anyone please suggest me a way to do it?

It depends on if you are using FXML or just coding.

But in any of these two ways the approach is the same:

you need to have both of your stages in variables. Then add an onAction event listener where it will trigger your stage 2 to be stage2.showAndWait() .

as for the textfield and the List. You need to add to that list with as simple arrayList.add(); then pass the new list to your listView FXController.ObservableArrayList(arrayList) then to update or "refresh" that listView it is kind of uncertain lately since there is no method to "refresh" but by setting listView.setVisible(false); and listView.setVisible(true) has done the trick!!

If you want it to be "automatic" you would have to add all that on your onAction event!

Good Luck

If you had code I would have provided a better example but I think I have addressed all the questions.

I took @James_D's advice and "refreshed" my ListView . I intended to add an item to ListView and update it based upon Button event.

I handled the button event in my controller and called refreshListView() if the item was sucessfully added to the list. Basically, I realized that the control is returned to the Stage1 controller once the stage2 is closed. So I wrote below code:

    @FXML
    private void handleAddNewItem(ActionEvent event) throws IOException {
        boolean flag = mNewBox.display();
        if(flag==true){
            refreshListView();
        }
    }

    public void refreshListView() {
        List<String> list = new ArrayList<String>();
        list = singleton.getFiles();

        items = FXCollections.observableArrayList(list);
        itemsListView.setItems(items);
    }

Thanks for the suggestions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM