用于关闭JDialog的按钮

问题描述:

我想在JDialog的底部添加一个按钮(JButton),按下时应关闭JDialog。问题是我不知道该按钮的ActionListener中要写什么。我不希望按钮退出程序,只需关闭对话框。

I want to add a button (JButton) at the bottom of a JDialog which should close the JDialog when pressed. The problem is I don't know what to write in the ActionListener of that button. I don't want the button to exit the program, just close the dialog.

JDialog是通过显式调用JDialog的一个构造函数而不是通过调用其中一个来创建的。来自JOptionPane的方法。

The JDialog is created by explicitly calling one of JDialog's constructors, not by calling one of the methods from JOptionPane.

我非常惊讶于我无法使用Google找到答案。我预计很多编程站点会广泛涵盖经常遇到的问题。非常奇怪,它不是。

I was extremely surprised that I was unable to find an answer to this using Google. I expected that a problem that is so often encoutered would be widely covered on a lot of programming sites. Pretty weird that it is not.

import java.awt.event.*;
import javax.swing.*;

public class YourDialog extends JDialog implements ActionListener {

  JButton button;

  public YourDialog() {
     button = new JButton("Close");
     button.addActionListener(this);
     add(button);
     pack();
     setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
      dispose();
  }
}




  • 关闭只使用 dispose()方法父框架未关闭的dialolg。 JVM未终止的原因。

    • close only dialolg using dispose() method parent frame not closed. reason that JVM not terminated.