有一个JFrame类中含有一个button按钮,点击按钮,弹出一个JDialog窗体,在弹出后想把JFrame隐藏,该怎么写

2025-02-21 08:31:56
推荐回答(5个)
回答1:

你看一下下边的代码。
把主窗体隐藏了,这样就关不掉主程序了,关掉JDialog,主程序还是运行的,只能在任务管理 器中关掉。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class A extends JFrame implements ActionListener {
boolean isError = false;

public A() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 300);
setResizable(false);
getContentPane().setLayout(null);
JButton btnNewButton = new JButton("open");
btnNewButton.addActionListener(this);
btnNewButton.setBounds(88, 32, 91, 21);
getContentPane().add(btnNewButton);
setVisible(true);
}

public static void main(String[] args) {
new A();
}

public void actionPerformed(ActionEvent e) {
new MyDialog();
this.setVisible(false);
}
}

class MyDialog extends JDialog {
public MyDialog() {
setSize(200, 100);
this.setVisible(true);
}
}

回答2:

大家的回答思路基本是对的(直接贴代码的忽略!!)
问题在于JDialog默认是Modal模式,也就是说setVisible()之后只有等关闭了JDialog才会继续执行后面的语句;另外,确实涉及到无法关闭主窗口的问题。

我的建议:将主窗口传递给JDialog,在JDialog的构造函数中,setVisible()之前把主窗口设为隐藏,在关闭JDialog的时候,可以选择将主窗口关闭,或让主窗口可见(估计此种方式比较合适)!

回答3:

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

/**
* Created by IntelliJ IDEA.
* User: DELL
* Date: 11-11-7
* Time: 下午2:40
* To change this template use File | Settings | File Templates.
*/
public class MyDear extends JFrame{
static JFrame frame = new JFrame("我是窗口");
static JButton button = new JButton("按钮");
public static void main(String[] args) {
frame.setBounds(0,0,300,300);
frame.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
frame.setVisible(false);
Object[] options = {"再次显示","继续隐藏"};
int response=JOptionPane.showOptionDialog(new MyDear(), "显示由我定",
"是否显示",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (response==1){
System.exit(1);
}
else {
frame.setVisible(true);
}
//To change body of implemented methods use File | Settings | File Templates.
}
});
frame.setVisible(true);
}
}

回答4:

假定Jframe 继承类名为 TT

button.addActionListener(new ActionListener(){
public void actionPerform(ActionEvent e)
{
new JDialog().setVisible(true);
TT.this.setVisible(false);

}

})

回答5:

dialog.setVisible(true);
frame.setVisible(false);
dialog.setModal(true); //注意, 模态状态放到后面做.