如何在关闭JFrame之前提示用户确认退出

时间:2014-05-02 13:01:21

标签: java swing jframe windowlistener

我有这个班级

package com.javacodegeeks.snippets.desktop;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.MouseListener;

import javax.swing.JFrame;

public class Main1 {

    public static void main(String args[]) {

        JFrame frame = new JFrame("Window Listener");

        WindowListener listener = new WindowAdapter() {

            public void windowClosing(WindowEvent w) {
                int response = JOptionPane.showConfirmDialog(null, " Are you sure you want isuue the ticket?", "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.YES_OPTION) {
                    System.exit(0);
                }
            }
        };

        frame.addWindowListener(listener);

        frame.setSize(300, 300);

        frame.setVisible(true);
    }
}

我的问题是,如果用户按"No" h / se将不再看到帧。 我希望用户能够回到主框架

我该怎么做?

2 个答案:

答案 0 :(得分:3)

待办事项

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

答案 1 :(得分:1)

if(response == JOptionPane.YES_OPTION)这是不正确的

    int confirm = JOptionPane.showConfirmDialog(null,"are you sure you want to Exit","Exit",JOptionPane.YES_NO_OPTION, 1);
    if(confirm == 0) // you have to do this {
    close();
    System.exit(0);
    }