Java - Methode pausieren bis ein JButton geklickt wurde?

1 Antwort

Vom Fragesteller als hilfreich ausgezeichnet

Achte darauf, dass dein Dialog modal ist. Dann werden auch andere Aktionen blockiert, so lange der Dialog geöffnet ist.

Entweder du nutzt dafür die entsprechende Konstruktorüberladung oder die setModal-Methode.

Beispiel:

public class ConfirmDialog extends JDialog {
  private boolean result;

  public ConfirmDialog(JFrame parent) {
    super(parent, "Confirm", true);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    JButton confirmButton = new JButton("OK");
    confirmButton.addActionListener(event -> {
      result = true;
      dispose();
    });
    add(confirmButton);
    pack();
  }

  public boolean showDialog() {
    result = false;
    setVisible(true);
    return result;
  }
}

// main:
SwingUtilities.invokeLater(() -> {
  JFrame frame = new JFrame("Example");
  frame.setLayout(new GridLayout(2, 1));
  JLabel label = new JLabel("false");
  frame.add(label);
  JButton button = new JButton("Open");
  button.addActionListener(event -> {
    ConfirmDialog dialog = new ConfirmDialog(frame);
    boolean confirmed = dialog.showDialog();
    label.setText(Boolean.toString(confirmed));
  });
  frame.add(button);
  frame.pack();
  frame.setVisible(true);
});