2

有没有办法在不退出整个应用程序的情况下使用取消按钮关闭框架。我试过关注

setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);

上面的行仅在我按下 X 关闭按钮关闭框架时才有效。有没有其他好的方法来实现一个 JButton 来执行相同的操作

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class CloseTestForm extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CloseTestForm frame = new CloseTestForm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CloseTestForm() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnSave = new JButton("Save");
        btnSave.setBounds(64, 141, 89, 23);
        contentPane.add(btnSave);

        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                //??
            }
        });
        btnCancel.setBounds(64, 192, 89, 23);
        contentPane.add(btnCancel);
    }
}
4

3 回答 3

4

使用任何东西作为setDefaultCloseOperation例外EXIT_ON_CLOSE

然后,对于取消按钮,只是dispose()窗口。如果应用程序有另一个正在运行的线程,它不会退出。您也可以通过调用隐藏窗口setVisible(false)

于 2012-11-08T14:55:01.010 回答
1

调用Window.dispose()摆脱框架。

您必须添加按钮并在按钮上添加 actionListener。然后在该actionPerformed动作侦听器的方法中,调用.dispose()要摆脱的帧上的方法。

于 2012-11-08T14:56:36.120 回答
1
  • 不要扩展JFrame,将其创建为局部变量

  • 然后你可以打电话myFrame.setVisible(false)

  • 以这种形式(此处发布的代码)当前的 JVM 永远不会过期,直到 PC 重新启动或关闭

  • 不要创建第二个或更多JFrame的,而是使用 JDialog

于 2012-11-08T14:57:40.553 回答