用按钮关闭JFrame [英] Closing JFrame with Button

查看:121
本文介绍了用按钮关闭JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用Eclipse的拖放功能,默认情况下,我有一个应用程序窗口随JFrame一起提供,并且能够setVisible(false);,但是我使用JPanel和扩展JFrame创建的其他框架/面板/窗口.

I am currently using Eclipse's drag and Drop feature, I have one application window which comes with JFrame by default and is able to setVisible(false); but my other frames/panel/window I have created with JPanel and with extending JFrame.

由于extend我无法setVisible(false or true);在窗口上仍然没有任何作用,所以它仍然保持为真.

Because of extend I am unable to setVisible(false or true); it has no effect at all on the window it still remains true.

我的代码:

private JPanel contentPane;

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

public LibrarianMenu() {
    setTitle("Librarian");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 385, 230);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    .
    .
    . so on

我在这里尝试执行我的按钮:

Here I am trying to execute my button:

 btnLogout.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    LibrarianMenu frame = new LibrarianMenu();
                    frame.setVisible(false);
                }
            });

有什么解决方案吗?

推荐答案

之所以发生这种情况,是因为每次您按下按钮时,都会创建该框架的新实例.这是您的代码已更新:

This is happening because every time you press the button you create a new instance of that frame. Here is your code updated :

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

注销按钮事件应如下所示:

And the logout button event should be like this :

btnLogout.addActionListener(
        new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
            }
        });

这篇关于用按钮关闭JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆