开发者

How to activate and deactivate frame in java?

I had made one application in java-swing,

Now what i am getting problem is,

i want to minimize my jframe when it is deactivate and then to maximize i want to activate that window.

So for maximize, i want to activate any jframe using java code.

So how to activate and dea开发者_如何学运维ctivate any jframe, so that i can do something on window listeners?

thanks in advance.


You'll need to add a WindowListener to your JFrame, and add the following logic to your listener:

public class Demo extends JFrame implements WindowListener {

    public Demo() {
        addWindowListener(this);
    }

    public void windowActivated(WindowEvent e) {
        setExtendedState(getExtendedState() | Frame.ICONIFIED);
    }

    public void windowDeactivated(WindowEvent e) {
        setExtendedState(getExtendedState() | Frame.MAXIMIZED_BOTH);
    }

    ....
}


The following works:

import java.awt.Frame;

import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) throws InterruptedException {

        // Create a test frame
        JFrame frame = new JFrame("Hello");
        frame.add(new JLabel("Minimize demo"));
        frame.pack();

        // Show the frame
        frame.setVisible(true);

        // Sleep for 5 seconds, then minimize
        Thread.sleep(5000);
        frame.setState(Frame.ICONIFIED);

        // Sleep for 5 seconds, then restore
        Thread.sleep(5000);
        frame.setState(Frame.NORMAL);

        // Sleep for 5 seconds, then kill window
        Thread.sleep(5000);
        frame.setVisible(false);
        frame.dispose();

        // Terminate test
        System.exit(0);
    }
}

Modified from http://www.javacoffeebreak.com/faq/faq0055.html


To focus the window you can do frame.requestFocus();.


In my practice, I often encountered a problem when the window is not activated when the usual attributes are set: frame.setVisible (true); frame.setState (Frame.NORMAL);

and I found a solution where the window is activated:

frame.setExtendedState (JFrame.ICONIFIED);
frame.setExtendedState (JFrame.NORMAL);
frame.toFront ();
frame.requestFocus ();

// frame - JFrame
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜