如何' undraw'一个图像?

时间:2014-03-14 06:57:15

标签: java image swing jframe draw

我正在尝试用Java制作一个简单的游戏,我需要做的就是在屏幕上绘制一个im,然后等待5秒然后“取消它”。

代码(此类在屏幕上绘制图像):

 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 Menu;
String LogoSource = "Logo.png";

public MainWindow() {
    ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource));
    Menu = ii.getImage();
    Timer timer = new Timer(5, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            repaint();

        }
});
    timer.start();

}   

public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null); 


    }
}

代码#2(这会创建JFrame)

package com.mainwindow.draw;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Frame extends JFrame {

public Frame() {
    add(new MainWindow());
    setTitle("Game Inviroment Graphics Test");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(640, 480);
    setLocationRelativeTo(null);
    setVisible(true);
    setResizable(false);


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

1 个答案:

答案 0 :(得分:3)

使用某种标志来确定是否应该绘制图像,并根据需要简单地改变它的状态......

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    if (draw) {
        g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null); 
    }
}

然后在需要时改变标志的状态......

Timer timer = new Timer(5, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        draw = false;
        repaint();
    }
});

注意:不建议覆盖paintpaint位于绘画更改的顶部,可以轻松破坏绘制过程的工作方式,从而导致问题无法解决。相反,通常建议使用paintComponent代替。有关详细信息,请参阅Performing Custom Painting

另请注意:javax.swing.Timer预计延迟时间以毫秒为单位...... 5有点快...