Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

java - Button for closing a JDialog

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.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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();
  }
}
  • close only dialolg using dispose() method parent frame not closed. reason that JVM not terminated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...