Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: How to close JDialog programmatically from a controller?

Tags:

java

swing

I've got a JDialog bound to my (separate) controller class via beans binding (Netbeans). My dialog has a "close" Button. The action property of this button is bound to an action in my controller.

Dialog:

public class AppVersionCheckDialog extends javax.swing.JDialog {
    ...
    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, controller, org.jdesktop.beansbinding.ELProperty.create("${closeButtonActionListener}"), btnOk, org.jdesktop.beansbinding.BeanProperty.create("action"));
    bindingGroup.addBinding(binding);
    ...
}

So basically I got

public class AppVersionCheckDialogController extends AbstractController {

    private final Action closeAction = new AbstractAction("Close") {
        @Override
        public void actionPerformed(ActionEvent e) {
            // dialog.dispose() - no reference of dialog instance here 
        }
    };


    public Action getCloseButtonActionListener(){
        return closeAction;
    }
}

in my controller.

I do not have any reference to the dialog within the controller. And I don't want to introduce one, as it breaks the whole principle of binding things together.

So how to close the dialog? Is there a way to bind the dialog instance to a property of my controller? If so, how?

like image 606
gorootde Avatar asked Dec 05 '25 07:12

gorootde


1 Answers

I don't have a compiler with me now, but if I understand correctly what you want is similar to this:

public void actionPerformed(ActionEvent e) {
        Component component = (Component) e.getSource();
        JDialog dialog = (JDialog) SwingUtilities.getRoot(component);
        dialog.dispose();
      }

I'll have a look when I have the chance to compile and if it has problems. I hope, it solves your problem.

like image 166
halil Avatar answered Dec 07 '25 21:12

halil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!