问题描述:

I've got a JDialog with a button that opens a new window. What I want to do is to block this JDialog whenever the other window opens. When I say block I mean that the user cannot manipulate it, not move it or maximisize or anything.

By the way, is it recommended to use JDialog for a window with buttons and a table? I stil don't get it when I have to use which frame!

This is what I've got:

public class Platos extends JDialog {

private final JPanel contentPanel = new JPanel();

public static void main(String[] args) {

try {

Platos dialog = new Platos();

dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

dialog.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

public Platos() {

setBounds(100, 100, 450, 300);

getContentPane().setLayout(new BorderLayout());

contentPanel.setLayout(new FlowLayout());

contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

getContentPane().add(contentPanel, BorderLayout.CENTER);

{

JButton btnAgregarPlato = new JButton("Agregar Plato");

btnAgregarPlato.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

AgregarPlato ap = new AgregarPlato();

ap.setVisible(true);

}

});

btnAgregarPlato.setFont(new Font("Tahoma", Font.PLAIN, 11));

contentPanel.add(btnAgregarPlato);

}

}

}

网友答案:

JDialog is the right choice indeed.

To make it block the parent window, you would have to add a constructor to Platos, which will utilise the JDialog constructor with parent frame:

JDialog dlg = new JDialog(parentWindow, modality);

Where parentWindow is typically a JFrame.

You do it like this:

public Platos(JFrame parent) {
    super(parent, ModalityType.APPLICATION_MODAL);
    ....

The trick is the ModalityType.APPLICATION_MODAL argument, which makes your dialog block all other dialogs and the main frame.

You can pass as parent the main window, it will work just fine even if you are opening the dialog from another one - the last one blocks all the previous ones.


For more reference, see the docs.

相关阅读:
Top