2014-03-14 47 views
0

我想在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(); 
    } 
} 

回答

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是一種快速...

+0

烏姆即時得到這個錯誤:在com.mainwindow.draw.MainWindow.paintComponent(主窗口.java:35) \t at javax.swing.JComponent.paint(Unknown Source) – user3349095

+0

這不算太多的錯誤信息......您是否在嘗試使用它之前聲明瞭'draw'變量? – MadProgrammer

+0

Hehehe,opps。正在調用'super.paint'而不是'super.paintComponent':P – MadProgrammer