简体   繁体   中英

Java JFrame Both Frames Show At the Same Time Issue

I am making a program which has two frames.When i run the program both frames open at a same time.I want that when i run the program the first frame is open for 2 seconds then auto hides and then the second frame should show up .

This is my code for frame 1:

public class Frame1 extends JFrame{

    private JLabel type;
    public Frame1(){    
    super("Frame 1");



    setLayout(null);
    type = new JLabel("This is Frame 1");
    type.setFont(new Font("Tahoma", Font.PLAIN, 51));
    type.setBounds(55, 227, 346, 52);
    add(type);


        setSize(500,600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setResizable(false);

        setVisible(true);

    }
}

Code for frame 2:

public class Frame2 extends JFrame{

    private JLabel text;

        public Frame2(){
        super("Frame 2");
        getContentPane().setLayout(null);
        text = new JLabel("This is Frame 2");
        text.setFont(new Font("Tahoma", Font.PLAIN, 36));
        text.setBounds(10, 66, 244, 52);
        getContentPane().add(text);


        setSize(300,350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);

    }


}

Main:

public class Main {
public static void main(String[] args) {

    Frame1 obj = new Frame1();

    Frame2 obj2 = new Frame2();

}

}

obj.setState(JFrame.ICONIFIED); You can use below code to get the first frame is open for 2 seconds then auto hide and then second frame:

public class Main { 

  public static void main(String[] args) {
Frame1 obj = new Frame1();
try {
    Thread.sleep(2000);
    obj.setState(JFrame.ICONIFIED);
} catch (Exception e) {
}
Frame2 obj2 = new Frame2();
  }
 }

Change you main class like this...

public class Main {
public static void main(String[] args) {

    Frame1 obj = new Frame1();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {      
        e.printStackTrace();
    }
    obj.setState(obj.ICONIFIED);

    Frame2 obj2 = new Frame2();

}

This will minimize your first frame and show the second frame .

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