简体   繁体   中英

What can I do in Java Swing to minimize the window (and not to close it) when the user click on the “x” button?

I am pretty new in Java Swing development and I have the following problem:

I have a class named MainFrame that extends JFrame to show a simple GUI.

This window have the classic "x" and "-" buton to close and to minimize the window.

If I click on the "x" button the window will be close. I think that this is the standard behavior definied by the JFrame abstrac class (is it correct or am I missing something?)

What can I do if I would that when the user click on the "x" button the window is not closed but only minimized? Have I to override a method? How?

Tnx

Andrea

Easily done. Set the frame's default close operation to "do nothing". Then provide a window listener that minimizes the frame from within the windowClosing method:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        ((JFrame)e.getSource()).setState(JFrame.ICONIFIED);
    }
});

I'd suggest not changing the close button behavior at all. It's bad practice to confuse the user. Instead, create a JFrame that is undecorated. It will no longer have borders, close buttons, or a title. And it won't be re-sizable, moveable, closeable, or minimizeable unless you specifically add those features in.

Use Window Listener:

import javax.swing.*;
import java.awt.event.*;

public class SwingFrame{
public static void main(String[] args) throws Exception{
    SwingFrame s = new SwingFrame();
    s.start();
}

JFrame frame;

public void start(){
    frame = new JFrame("Frame in Java Swing");
    frame.getContentPane().add(lbl);
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new myWindowListener());
}
class myWindowListener implements WindowListener{
    public void windowClosing(WindowEvent e){
        System.out.println("hi");
        frame.setState(JFrame.ICONIFIED);
    }
    public void windowActivated(WindowEvent e){}

    public void windowClosed(WindowEvent e){}

    public void windowDeactivated(WindowEvent e){}

    public void windowDeiconified(WindowEvent e){}

    public void windowIconified(WindowEvent e){}

    public void windowOpened(WindowEvent e){}
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM