【问题标题】:Is there any way to Close the JFrame without exiting the whole application using Cancel jButton?有什么方法可以关闭 JFrame 而无需使用 Cancel jButton 退出整个应用程序?
【发布时间】:2012-11-08 14:52:37
【问题描述】:

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

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);
    }
}

【问题讨论】:

标签: java swing jbutton jform


【解决方案1】:

setDefaultCloseOperation 使用除EXIT_ON_CLOSE 之外的任何内容。

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

【讨论】:

    【解决方案2】:

    致电Window.dispose() 删除框架。

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

    【讨论】:

      【解决方案3】:
      • 不要扩展 JFrame,将其创建为局部变量

      • 那您可以拨打myFrame.setVisible(false)

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多