0

我想要做的是,当我运行我的应用程序时,它会启动线程并且图像显示 3 秒(3000 毫秒),然后线程停止运行。

图片路径正确,图片文件存在,线程本身运行;但是,图像似乎没有显示。有什么问题?这是我的代码:

package org.main;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Splasher extends JPanel implements Runnable {
    private static final long serialVersionUID = 1L;
    Image image;
    ImageIcon splash = new ImageIcon("res/splash.png");
    public static Thread DrawSplash = new Thread(new Splasher());

    public Splasher() {
        setFocusable(true);
        image = splash.getImage();  
        repaint();
    }
    boolean hasRan = false;
    public void run() {
        try {
            System.out.println("Drawing Splash Screen");
            repaint();
            Thread.sleep(3000);
            System.out.println("Repainted");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }

    public Image getImage() {
        return image;
    }
}
4

2 回答 2

2

你的问题还不够。

你没有展示你如何使用启动画面,如果它附加到任何东西或你如何启动/使用Thread.

所以问题可能是任何...

除了 VishalK 已经指出的所有其他内容,我想补充public static Thread DrawSplash = new Thread(new Splasher())的是一个坏主意。你不应该使用static Threads 因为线程是不可重入的,也就是说,你可以运行同一个线程两次。

这是一个小例子,展示了一个“褪色”的闪屏,使用了一些 Swing Timers

这假设您使用的是 Java 7,它还可以用于 Java 6,我还没有发布该代码。

public class TestSplashScreen01 {

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

    public TestSplashScreen01() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                SplashScreen splash = new SplashScreen();
                splash.start();

            }
        });
    }

    public class SplashScreen extends JWindow {

        private SplashPane splash;

        public SplashScreen() {
            setBackground(new Color(0, 0, 0, 0));
            splash = new SplashPane();
            add(splash);
            pack();
            setLocationRelativeTo(null);
        }

        public void start() {
            splash.start();
        }

        public class SplashPane extends JPanel {

            private BufferedImage splash;
            private Timer timer;
            private float alpha = 0f;
            private int duration = 1000;
            private long startTime = -1;

            public SplashPane() {
                try {
                    splash = ImageIO.read(getClass().getResource("/res/SokahsScreen.png"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                timer = new Timer(3000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        fadeOut();
                    }
                });
                timer.setRepeats(false);
            }

            protected void fadeOut() {
                Timer fadeInTimer = new Timer(40, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        long now = System.currentTimeMillis();
                        long runTime = now - startTime;
                        alpha = 1f - ((float) runTime / (float) duration);
                        if (alpha <= 0.01f) {
                            alpha = 0f;
                            ((Timer) (e.getSource())).stop();
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    dispose();
                                }
                            });
                        }
                        repaint();
                    }
                });
                startTime = System.currentTimeMillis();
                fadeInTimer.setRepeats(true);
                fadeInTimer.setCoalesce(true);
                fadeInTimer.start();
            }

            protected void fadeIn() {
                Timer fadeInTimer = new Timer(40, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        long now = System.currentTimeMillis();
                        long runTime = now - startTime;
                        alpha = (float) runTime / (float) duration;
                        if (alpha >= 1f) {
                            alpha = 1f;
                            ((Timer) (e.getSource())).stop();
                            timer.start();
                        }
                        repaint();
                    }
                });
                startTime = System.currentTimeMillis();
                fadeInTimer.setRepeats(true);
                fadeInTimer.setCoalesce(true);
                fadeInTimer.start();
            }

            public void start() {
                if (!SplashScreen.this.isVisible()) {
                    alpha = 0f;
                    SplashScreen.this.setVisible(true);
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            fadeIn();
                        }
                    });
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return splash == null ? super.getPreferredSize() : new Dimension(splash.getWidth(), splash.getHeight());
            }

            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (splash != null) {
                    Graphics2D g2d = (Graphics2D) g.create();
                    g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
                    int x = (getWidth() - splash.getWidth()) / 2;
                    int y = (getHeight() - splash.getHeight()) / 2;
                    g2d.drawImage(splash, x, y, this);
                    g2d.dispose();
                }
            }
        }
    }
}

注意:

这个例子的问题是一旦你调用 start,程序会继续执行,这需要某种监听器在启动画面完成时告诉感兴趣的各方。

或者,您可以使用未装饰的模式JDialog

于 2013-02-16T21:35:40.217 回答
1

您在代码中犯的许多错误...

  1. 您有重写paint方法而不是paintComponent绘制图像。
  2. 您已用于在组件 ( )Thread上绘制和删除图像。您应该改用javax.swing.TimerSwingJPanel
  3. 尽管您应该使用javax.swing.Timer,但您犯的基本错误仍然是您创建了一个静态线程并在其中传递了一个新对象Splasher而不是当前对象。
  4. 每次您想在图形中进行更改时,Component您都应该repaint显式调用。例如,如果您想让图像在 3 秒后消失,您应该repaint在 3 秒 laps 后调用方法,并且应该在paintComponent方法中写入适当的逻辑来删除该图像。

这是您的代码的修改版本,它完全符合您的要求。看看它。:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.SwingUtilities;

public class Splasher extends JPanel {

    private static final long serialVersionUID = 1L;
    Image image;
    ImageIcon splash = new ImageIcon("apple.png");
    MyComponentListener componentListener ;
    Timer timer ;

    public Splasher() 
    {
        componentListener = new MyComponentListener();
        setFocusable(true);
        image = splash.getImage();  
        timer = new Timer(3000, new LoadAction());
        addComponentListener(componentListener);
     }
    boolean hasRan = false;

    @Override
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        if (image == null && timer !=null )
        {
            g.clearRect(0, 0, getWidth(), getHeight()) ;
            timer.stop();
            removeComponentListener(componentListener);
        }
        else
        {
            g.drawImage(image, 0, 0, null);
        }
    }
    public Image getImage() 
    {
        return image;
    }
    private class MyComponentListener extends ComponentAdapter
    {
        @Override
        public void componentResized(ComponentEvent evt)
        {
            System.out.println("Resized..");
            timer.start();
        }
    }
    private class LoadAction implements ActionListener 
    {
        public void actionPerformed(ActionEvent evt)
        {
            System.out.println("Drawing Splash Screen");
            repaint();
            image = null;
            repaint();
            System.out.println("Repainted");
        }

    }
    public static void main(String st[])
    {
        SwingUtilities.invokeLater ( new Runnable()
        {
            @Override
            public void run()
            {
                JFrame frame = new JFrame("Splash:");
                frame.getContentPane().add(new Splasher());
                frame.setSize(300,500);
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}

另请观看以下有关 java 中的 Paint 机制的教程。 http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html

于 2013-02-16T21:52:04.507 回答