简体   繁体   中英

Java hide JFrame1 and JFrame2, when JFrame0 is deactivated?

is there a way to hide all the other JFrames of my application, when the user clicks out of the "mainFrame"?

I tried with this

   public void windowActivated(WindowEvent we) {
        frame1.setVisible(true);
        frame.setVisible(true);
    }

    public void windowDeactivated(WindowEvent we) {
        frame1.setVisible(false);
        frame2.setVisible(false);
    }`

but this doesn't work. All of my Windows start blinking. I cannot set JFrame2 unfocusable.

Is there any other way to do this?

Use non-modal dialogs instead and the problem is sorted by default.

import javax.swing.*;

class TestDialogMinimize {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                JFrame f = new JFrame("Has a Dialog");

                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setSize(400,400);

                JDialog d = new JDialog(f);
                d.setSize(200,200);
                f.setVisible(true);
                d.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

The non-modal dialog suggestion in this answer is one way to go. See also this answer elsewhere .

If for some reason you need to continue using frames, you can minify them with

frame1.setState(Frame.ICONIFIED)

and raise them with

frame1.setState(Frame.NORMAL)

Handle these in a code block like:

frame0.addWindowStateListener(new WindowStateListener() {

        @Override
        public void windowStateChanged(WindowEvent e) {
                // handle change
        }
    });

as described in this question's answers .

If you want to close all frames when the frame0 is closed, you can use:

frame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

to exit the program and close all frames when the frame0 is closed. If you are just hiding on close use a window listener. You can use frame1.setVisible(false) in your WindowListener .

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