需要帮助在Java中绘制图像

时间:2014-03-14 19:35:23

标签: java image swing timer paintcomponent

我要做的是在屏幕上显示一个图像显示x秒,然后消失,然后在其位置绘制另一个图像,我有第一个要显示的图像,但第二个图像没有显示。工作。 注意:我可以绘制形状但不能绘制图像

package com.mainwindow.draw;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

@SuppressWarnings("serial")
public class MainWindow extends JPanel {

Image Logo;
Image Menu;
String LogoSource = "Gimijes.png";
String menuEntity = "Menu.png";
Boolean draw = true; 

static Boolean timeout = false;

public MainWindow() {
    ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource));
    Logo = ii.getImage();
    ImageIcon mii = new ImageIcon(this.getClass().getResource(menuEntity));
    Menu = mii.getImage();
    Timer timer = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            draw = false;
            timeout = true;
            repaint();

        }
    });

    timer.start();
};

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    if (draw == true) {
        //draw Gimijes.png (on screen for 5 seconds)
        g2.drawImage(Logo, 0, 0, null);             
    }
    if (timeout  == true) {
        g2.drawImage(Menu, getWidth(), getHeight(), null);

    }       
    }   
}

如果有人知道如何让这个工作,我会非常感激。

1 个答案:

答案 0 :(得分:1)

问题在于新图像的位置。如果要覆盖现有图像,则使用相同的坐标(位置[0,0])。

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    if (draw == true) {
        // draw Gimijes.png (on screen for 5 seconds)
        g2.drawImage(Logo, 0, 0, null);
    }
    if (timeout == true) {
        g2.drawImage(Menu, 0, 0, null);
    }
}
相关问题