简体   繁体   中英

JWindow - doesn't show

I have a problem with JWindow.

This is my class that contsins JWindow:

public class NextLevelCounter {
    JWindow window = new JWindow();

    public static void main(String[] args) {
        new NextLevelCounter();
    }

    public NextLevelCounter() {
        window.getContentPane().add(new JLabel("Waiting"));
        window.setBounds(0, 0, 300, 200);
        window.setVisible(true);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        window.dispose();
    }
}

It workes fine when i run main() from NextLevelCounter class but when I try do run it from another class it doesn't show. For example:

This is in another class:

private void isGameFinished() {
    if(food.size() > 0)
        return;
    else if(food.size() == 0) {
        timer.stop();
        System.out.println("I am here");
        new NextLevelCounter();
        System.out.println("I am here 2");
        this.level++;
    }
}

Both "I am here" and "I am here 2" shows up with 5000ms difference (as it should) but the window doesn't show.

What am I doing wrong?

EDIT:

I am using JWindow because I want an empty window without any borders.

The sleeping thread cant display the window. Although it does in your first example, that is bad practice. Use a swing worker to close the window after 5 seconds:

public class NextLevelCounter {
    JWindow window = new JWindow();

    public static void main(String[] args) {
        new NextLevelCounter();
    }

    public NextLevelCounter() {
        window.getContentPane().add(new JLabel("Waiting"));
        window.setBounds(0, 0, 300, 200);
        window.setVisible(true);

        //Create a worker that whill close itself after 5 seconds. The main thread
        //is notified and will dispose itself when worker finishes
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
           @Override
           protected Void doInBackground() throws Exception {
                 Thread.sleep(5000);
                 return null;
           }

           protected void done() {
               window.dispose();
           }
      };

      worker.execute();
    }
}

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