how to close jdialog from a button?

java, jdialog, modal-dialog, swing

Solution

can i change the modal of dialog after i create instance of it?

yes you can to change `setModal` or `ModalityTypes` on runtime, but for code in this form doesn't make me any sence

how to close jdialog from that button (inside jdialog)?

in this case doesn't matter if you'll to call `setVisible` or `dispose()`

create `JDialog` only one time,

create that as local variable

change `myDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);`, then `button` in the `toolbar` (with `X`) to hide `JDialog` too

then you can to call from `actionPerformed` only `myDialog.setVisible(true)` and `ModalityType` too if required, setVisible shoud be wrapped in `invokeLater()`, instead of creating a new instance (`new Dialogz(this, true);` )

`JButton` placed in `JDialog` will be called only `myDialog.setVisible(false)`

example corresponding with your logics

Problem

i have a Jframe (Mainz), it have a button (showDialog), when user click the button, jdialog (Dialogz) will show, that jdialog have a button - how to close jdialog from that button (inside jdialog)? - can i change the modal of dialog after i create instance of it? i need to block the owner of that jdialog heres i try ... ``` import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; public class Mainz extends JFrame implements ActionListener{ JButton showDialog = new JButton("show dialog"); public Mainz() { setLayout(new FlowLayout()); showDialog.addActionListener(this); add(showDialog); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { new Dialogz(this, true); } public static void main(String[]args){ new Mainz(); } } class Dialogz extends JDialog{ JButton close = new JButton("close"); public Dialogz(JFrame owner,boolean modal) { super(owner, modal); System.out.println(this.getModalityType()); add(close); setLocationRelativeTo(owner); setVisible(true); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ closez(); } }); } void closez(){ setModal(false); this.dispose(); System.out.println("Method Done"); } } ``` thanks a lot for any kind of help

Original source

Related problems