首页javajdialogJava Swing - 如何从对话框获取值而不关闭它

Java Swing - 如何从对话框获取值而不关闭它

我们想知道如何从对话框获取值而不关闭它。
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class Main extends Box {
  JFrame frame;
  JTextArea text = new JTextArea("this is a test");

  public Main(JFrame frame) {
    super(BoxLayout.Y_AXIS);
    this.frame = frame;
    add(text);
    JButton button = new JButton("Click Me");
    button.addActionListener(e -> launchDialog());
    add(button);
  }

  public void launchDialog() {
    JButton findButton = new JButton("Find");
    findButton.addActionListener(e -> {
      int start = text.getText().indexOf("is");
      int end = start + "is".length();
      if (start != -1) {
        text.requestFocus();
        text.select(start, end);
      }
    });
    JButton cancelButton = new JButton("Cancel");

    JOptionPane optionPane = new JOptionPane("Do you understand?", JOptionPane.QUESTION_MESSAGE,
        JOptionPane.YES_NO_OPTION, null, new Object[] { findButton,
            cancelButton });

    JDialog dialog = new JDialog(frame, "Click a button", false);
    cancelButton.addActionListener(e -> dialog.setVisible(false));
    dialog.setContentPane(optionPane);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.setLocation(100, 100);
    dialog.pack();
    dialog.setVisible(true);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Main(frame));
    frame.pack();
    frame.setVisible(true);
  }
}