Java图形界面GUI的问题

如何对JDialog的弹窗设置点击窗体右上角叉号关闭?如何对JDialog的弹窗设置点击窗体右上角叉号关闭?

  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7452517
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:Java GUI:不用JDialog实现窗口跳转后无法操作原窗口
  • 除此之外, 这篇博客: Java图形界面编程--对话框JDialog(模态对话框,非模态对话框)中的 对话框JDialog(模态对话框,非模态对话框) 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • package com.lddx.day0309;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    //对话框JDialog(模态对话框,非模态对话框)
    public class TestDialog {
    	public static void main(String[] args) {
    		
    		TestDialog d=new TestDialog();
    		d.init();
    	}
    	JFrame f=new JFrame();
    	public void init(){
    		
    		JPanel p=new JPanel();
    		JButton b1=new JButton("模态按钮");
    		JButton b2=new JButton("非模态按钮");
    		
    		//把内部类绑定到按钮
    		MyListener ml=new MyListener();
    		b1.addActionListener(ml);
    		b2.addActionListener(ml);
    		
    		p.add(b1);
    		p.add(b2);
    		f.add(p);
    		
    		f.setTitle("对话框");
    		f.setSize(600, 600);
    		f.setVisible(true);
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    	//定义内部类实现接口ActionListener接口
    	public class MyListener implements ActionListener{
    
    		public void actionPerformed(ActionEvent e) {
    			String str=e.getActionCommand();//获得事件源内容
    			System.out.println(str);	
    			if(str.equals("模态按钮"))
    			{
    				JDialog  d=new JDialog(f,"模态对话框");
    				d.setModal(true);//设置对话框为模态对话框
    				d.setSize(300, 300);
    				d.setTitle("What are doing!");
    				d.setVisible(true);//设置对话框可见
    			}
    			else
    			{
    				JDialog  d=new JDialog(f,"非模态对话框");
    				d.setModal(false);//设置对话框为非模态对话框
    				d.setSize(300, 300);
    				d.setTitle("你弄啥嘞!");
    				d.setVisible(true);//设置对话框可见
    			}
    		}
    	}
    }
    
    
  • 以下回答由chatgpt基于相关博客总结生成:

    回答:

    可以使用以下代码来设置JDialog的关闭方式:

    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    

    其中,d为JDialog的实例化对象。该代码会在JDialog被关闭时销毁该对话框,实现关闭操作。完整代码如下:

    JDialog  d=new JDialog(f, "模态对话框");
    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    d.setModal(true);//设置对话框为模态对话框
    d.setSize(300, 300);
    d.setTitle("What are doing!");
    d.setVisible(true);//设置对话框可见
    
    JDialog  d=new JDialog(f, "非模态对话框");
    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    d.setModal(false);//设置对话框为非模态对话框
    d.setSize(300, 300);
    d.setTitle("你弄啥嘞!");
    d.setVisible(true);//设置对话框可见
    

    其中,也可以将参数DISPOSE_ON_CLOSE替换成其他选项,如HIDE_ON_CLOSE等,具体使用可以根据不同情况自行选择。