Java 如何在不关闭主程序的情况下关闭 jframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4268749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:12:43  来源:igfitidea点击:

How to close a jframe without closing the main program

javauser-interface

提问by Jon

I'm creating a program to keep track of a list of DVD's. On the main page I have set up 2 JButtons. When the user clicks the one that says new, a new JFrame from another class comes up with fields to enter information about a new DVD. I'm trying to make a cancel button on this second frame work so that when one clicks the cancel button, it brings back up the main GUI and closes the new entry GUI. Code is below, I cant figure out how to do it.

我正在创建一个程序来跟踪 DVD 列表。在主页上,我设置了 2 个 JButton。当用户单击显示为 new 的那个时,来自另一个类的新 JFrame 会出现用于输入有关新 DVD 的信息的字段。我正在尝试在第二个框架上制作一个取消按钮,以便当单击取消按钮时,它会返回主 GUI 并关闭新的条目 GUI。代码如下,我不知道怎么做。

Main GUI page

主 GUI 页面

package dvdlibrary;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


public class bootPage extends javax.swing.JFrame {

    /** Creates new form bootPage */
    public bootPage() {
        initComponents();
    }



    @SuppressWarnings("unchecked")

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("DVD Library");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(168, 11, -1, -1));

        jLabel2.setText("What would you like to do today?");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(113, 70, -1, -1));

        jButton1.setText("Create Record");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 135, -1, -1));

        jButton2.setText("View Library");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(224, 135, 111, -1));

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         




    }                                        

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
      if(evt.getSource()== jButton1)
           dvdlibrary.createEntry.createE();


    }                                     

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
       if(evt.getSource()== jButton2)
           dvdlibrary.movieChooser.movChoo();
    }                                     


    public static void bootP() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new bootPage().setVisible(true);
                new bootPage().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;


}

Create Entry page

创建入口页面

package dvdlibrary;

public class createEntry extends javax.swing.JFrame {


    public createEntry() {
        initComponents();
    }


    @SuppressWarnings("unchecked")

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jComboBox1 = new javax.swing.JComboBox();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Title");

        jLabel2.setText("Genre");

        jLabel3.setText("Length");

        jLabel4.setText("Rating");

        jLabel5.setText("Description");

        jLabel6.setText("Year");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Input");

        jButton2.setText("Load");

        jButton3.setText("Save");

        jButton4.setText("Cancel");
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel6))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField2)
                                    .addComponent(jTextField4)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(124, 124, 124)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(jButton4)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)))
                .addGap(23, 23, 23))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(37, 37, 37)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(39, 39, 39)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton3)
                        .addComponent(jButton2)
                        .addComponent(jButton4)))
                .addContainerGap())
        );

        pack();
    }                       

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {                                      


    }                                     


    public static void createE() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new createEntry().setVisible(true);

            }
        });
    }


    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration                   

}

回答by dacwe

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)

回答by npinti

I think you can also use DISPOSE_ON_CLOSE:

我想你也可以使用DISPOSE_ON_CLOSE

DISPOSE_ON_CLOSE (the default for JInternalFrame)

Hide and dispose of the window when the user closes it. This removes the window from the screen and frees up any resources used by it.

DISPOSE_ON_CLOSE(JInternalFrame 的默认值)

当用户关闭窗口时隐藏并处理它。这会从屏幕上移除窗口并释放它使用的所有资源。

回答by camickr

Did you read the API to find out other values for the setDefaultCloseOperation(...) method?

您是否阅读了 API 以找出 setDefaultCloseOperation(...) 方法的其他值?

You can use:

您可以使用:

DISPOSE_ON_CLOSE - the frame will close. If this is the last open frame for the application then the JVM will terminate as well

DISPOSE_ON_CLOSE - 框架将关闭。如果这是应用程序的最后一个打开帧,则 JVM 也将终止

HIDE_ON_CLOSE - the frame is just set to invisible.

HIDE_ON_CLOSE - 框架设置为不可见。

when user clicks the one that says new a new jframe from another class comes up with fields to enter information about a new dvd.

当用户单击说 new 的那个时,另一个类的新 jframe 会出现用于输入有关新 DVD 的信息的字段。

The real problem with your program is that you are using a frame as the popup window. You should be using a modal JDialog. An application should only ever have a single JFrame with multiple dialogs to gather additional information. A JDialog does not allow you to use EXIT_ON_CLOSE.

您的程序的真正问题在于您使用框架作为弹出窗口。您应该使用模态 JDialog。一个应用程序应该只有一个带有多个对话框的 JFrame 来收集额外的信息。JDialog 不允许您使用 EXIT_ON_CLOSE。

回答by ThePersonWithoutC

I had a similar problem and used jFrameInstanceVariable.setVisible(false);as the action that occured when I hit my CANCEL button. But every time I clicked the button that popped up the JFrame afterward, all the old content was still there in addition to the new content created from pressing the button.

我有一个类似的问题,并用作jFrameInstanceVariable.setVisible(false);我点击取消按钮时发生的操作。但是每次我点击弹出 JFrame 的按钮时,除了按下按钮创建的新内容之外,所有旧内容仍然存在。

I fixed this by making a new instance of JFrame every time the button is pressed that pops up the JFrame.

我通过在每次按下弹出 JFrame 的按钮时创建一个新的 JFrame 实例来解决这个问题。

回答by Xenonic

To hide the window without it actually closing the program, do:

要隐藏窗口而不实际关闭程序,请执行以下操作:

f.setVisible(false);

回答by user2549333

If this is the case, make sure to use setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);on your JFrame when initializing, not setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

如果是这种情况,请确保setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);在初始化时在 JFrame上使用,而不是 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  • DISPOSE_ON_CLOSE will terminate your application when the last JFrame is closed. EXIT_ON_CLOSE will terminate your application as soon as that JFrame is closed. HIDE_ON_CLOSE (default) will not terminate your application even if all JFrames are hidden.
  • DISPOSE_ON_CLOSE 将在最后一个 JFrame 关闭时终止您的应用程序。一旦 JFrame 关闭,EXIT_ON_CLOSE 将终止您的应用程序。即使隐藏了所有 JFrame,HIDE_ON_CLOSE(默认)也不会终止您的应用程序。

回答by Normen Yu

If you just hide the program, using HIDE_ON_CLOSEor set.Visible(false), that is not a very good choice, because if you do something larger with more frames, the hidden frames will still be running, slowing down computer performance. The way, as other have said, is instead of using setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, which will terminate the program when you click "X, closing all of the frames, use the following:

如果你只是隐藏程序,使用HIDE_ON_CLOSEset.Visible(false),那不是一个很好的选择,因为如果你用更多的帧做更大的事情,隐藏的帧仍然会运行,降低计算机性能。正如其他人所说,方法是代替 using setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);,当您单击“X,关闭所有框架时,它将终止程序,使用以下内容:

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

回答by Stephen

If your using a button like I think you said you were

如果你使用一个按钮,就像我认为你说的那样

this.dispose();

will do the trick..

会做的伎俩..

回答by Novzmerz24

Try putting this.dispose();inside the cancel button method.

尝试放入this.dispose();取消按钮方法。