Java Timer:我想淡入淡出我的图片,但是有一些错误

时间:2014-04-17 15:45:43

标签: java swing timer paint

这是我的代码,当我运行该程序时,它正在按我的意愿工作,但有一些错误,我不知道如何解决它,请帮助。

public class FadeTimer extends JPanel {

    static Image image;
    Timer timerin;
    Timer timerout;
    private float alpha = 0f;
    static int width;
    static int height;
    static Dimension screen;

    public FadeTimer() throws IOException {

        this.setBackground(Color.black);

        this.setLayout(new BorderLayout());

        // create timer with 100 delay and add action perform of this method
        timerin = new Timer(100, new actionfadein());
        timerin.start();

        timerout = new Timer(100, new actionfadeout());
        timerout.start();

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                alpha));
        g2d.drawImage(image, (screen.width - width) / 2,
                (screen.height - height) / 2, null);

    }

    public static void main(String[] args) throws IOException {

        JFrame frame = new JFrame("fade frame");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.add(new FadeTimer());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // set picture in the center of screen
        frame.setVisible(true);

        image = new ImageIcon(ImageIO.read(new File("gummybear.jpg")))
                .getImage();
        width = image.getWidth(frame);
        height = image.getHeight(frame);
        Toolkit tk = frame.getToolkit();
        screen = tk.getScreenSize();

    }

    class actionfadein implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            System.out.println(alpha);
            alpha += 0.1f;
            if (alpha > 1) {
                alpha = 1;
                timerin.stop();
            }
            repaint();

        }
    }

    class actionfadeout implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            System.out.println(alpha);
            alpha -= 0.05f;
            if (alpha < 0) {
                alpha = 0;
                timerout.stop();
            }
            repaint();

        }
    }

}

/////////////////////////////////////////////// /

1 个答案:

答案 0 :(得分:0)

不使用JFrame实例的屏幕尺寸:

    screen = Toolkit.getDefaultToolkit().getScreenSize();

在创建JFrame之后,添加一个组件侦听器以更新任何调整大小的宽度和高度:

    JFrame frame = new JFrame("fade frame");
    frame.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            width = image.getWidth(frame);
            height = image.getHeight(frame);
        }
    });