2

我正在使用 JWindow 在应用程序启动期间显示我的启动画面。但是它不会出现在所有窗口的前面,它也不会消失。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;

public class MySplash {
    public static MySplash INSTANCE;
    private static JWindow jw;

    public MySplash(){
        createSplash();
    }

    private void createSplash() {
        jw = new JWindow();
        JPanel content = (JPanel) jw.getContentPane();
        content.setBackground(Color.white);

        // Set the window's bounds, centering the window
        int width = 328;
        int height = 131;
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screen.width - width) / 2;
        int y = (screen.height - height) / 2;
        jw.setBounds(x, y, width, height);

        // Build the splash screen
        JLabel label = new JLabel(new ImageIcon("splash.jpg"));
        JLabel copyrt = new JLabel("SplashScreen Test",
            JLabel.CENTER);
        copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12));
        content.add(label, BorderLayout.CENTER);
        content.add(copyrt, BorderLayout.SOUTH);
        Color oraRed = new Color(156, 20, 20, 255);
        content.setBorder(BorderFactory.createLineBorder(oraRed, 0));

    }

    public synchronized static MySplash getInstance(){
        if(INSTANCE==null){
            INSTANCE = new MySplash();
        }

        return INSTANCE;

    }

    public void showSplash(){
        jw.setAlwaysOnTop(true);
        jw.toFront();
        jw.setVisible(true);
        return;
    }

    public void hideSplash(){
        jw.setAlwaysOnTop(false);
        jw.toBack();
        jw.setVisible(false);
        return;
    }
}

因此,在我扩展 JFrame 的主类中,我将启动画面称为

    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run() {
            MySplash.getInstance().showSplash();
        }

    });

但是,JWindow 出现在我计算机上所有打开的窗口实例的后面。隐藏 JWindow 也不起作用。

    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run() {
            MySplash.getInstance().hideSplash();
        }

    });
4

1 回答 1

4

你可能想看看java.awt.SplashScreen。但是,如果您对解决方案下定了决心:

看着Window#toFront

如果此 Window 可见,则将此 Window 置于最前面并可能使其成为焦点 Window。

JWindow在将其带到前面之前,请尝试使其可见。

我不确定你为什么JWindow不隐藏,那部分对我有用。

/e1
如果您尝试实现单例模式,则应将构造函数和字段设为私有。您可能还想看看什么是在 Java 中实现单例模式的有效方法?.

/e2和方法末尾的 s
是不必要的,无论如何,该方法都会在那时返回。returnshowSplashhideSplash

于 2011-11-30T02:20:56.460 回答