سؤال

I am trying to make a simple game in Java, All i need to do is draw an im onto the screen and then wait for 5 seconds then 'undraw it'.

Code (this class draws the image on the screen):

 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); 


    }
}

Code #2 (this creates the 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();
    }
}
هل كانت مفيدة؟

المحلول

Use some kind of flag to determine if the image should be drawn or not and simply change it's state as needed...

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

Then change the state of the flag when you need to...

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

Note: It's not recommended to to override paint, paint is at the top of the paint change and can easily break how the paint process works, causing no end of issues. Instead, it's normally recommended to use paintComponent instead. See Performing Custom Painting for more details

Also note: javax.swing.Timer expects the delay in milliseconds...5 is kind of fast...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top