Java listener on dialog close
Asked Answered
D

2

24

I have a Java app that displays a list from a database. Inside the class is the following code to open a new dialog for data entry:

@Action
public void addNewEntry() {
    JFrame mainFrame = ADLog2App.getApplication().getMainFrame();
    addNewDialog = new AddNewView(mainFrame, true);
    addNewDialog.setLocationRelativeTo(mainFrame);
    addNewDialog.addContainerListener(null);
    ADLog2App.getApplication().show(addNewDialog);
}

How do you add a listener to the main class to detect when the addNewDialog window is closed, so that I can call a refresh method and refresh the list from the database.

Dear answered 4/10, 2011 at 19:5 Comment(4)
What do you mean by the "main class"? The class that defines addNewEntry? The JFrame? What the heck is AddNewView? What library is that from?Milicent
Have you looked into Windowlisteners? download.oracle.com/javase/1.4.2/docs/api/java/awt/event/…Leelah
Sorry, 'AddNewView' is the JDialog being opened.Dear
Since Simiil's link from 2011 now points to the starting page of the JDK 20 documentation here is the same documentation (WindowListener), but from JDK 8. This link should hopefully hold until at least 2030: docs.oracle.com/javase/8/docs/api/java/awt/event/… and in JDK 20: docs.oracle.com/en/java/javase/20/docs/api/java.desktop/java/…Chandless
P
53

If AddNewView is a Window such as a Dialog or JDialog, you could use the Window.addWindowListener(...). That is, in your main class, you do

addNewDialog.addWindowListener(someWindowListener);

where someWindowListener is some WindowListener (for instance a WindowAdapter) which overrides / implemetnns windowClosed.

A more complete example, using an anonymous class, could look like

addNewDialog.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosed(WindowEvent e) {
        refreshMainView();
    }
});

Relevant links:

Plotinus answered 4/10, 2011 at 19:9 Comment(4)
Great links. In regard to the ones to the JavaDocs. Until such times as bug report 7090875 (an RFE) is resolved, any chance of you throwing a '7' into any search for the doc for a class (or otherwise linking to the version 7 docs)?Cary
Yeah. Perhaps it's time to start referring to v7... Hadn't struck my mind. I'll do it from now on. Thanks.Plotinus
Thanks back. The sooner that people start linking to the v. 7 docs, the sooner Google will return those links over the v. 6 links. Of course, if the RFE is implemented, it will all become moot.Cary
Just to add note that windowClosed is called when dispose() method are used, and windowClosing is called when user press 'X' button on top-right of the JDialog.Nijinsky
S
8

you have to add WindowListener and override windowClosing Event, if event occured then just returs some flag, example here

Schoolbag answered 4/10, 2011 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.