简体   繁体   中英

Java won't draw my image when method is called using threads

I have this flower program where it is supposed to drop flowers from above.... I need it to wait a few seconds then call the method to drop the flower. I know the method runs because i have it print out the falling y values. But it won't draw it on the screen. I really don't know what I'm doing wrong. Here is some of the code...

    //Ignore starting here
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    //Ignore ending here

    public class RedFlower implements ActionListener{
        Timer time;
        ImageIcon i = new ImageIcon("graphics//flowers//red_flower.png");
        Image flower = i.getImage();
        int y, x;
        int dy = 1;
        public void dropFlower(){
            Random rnd = new Random();
            y = 50;
            x = rnd.nextInt(1216);
            time = new Timer(5, this);
            time.start();
}
public void actionPerformed(ActionEvent e){// used for stoping the timer when off the screen
    int checky = y++;
    if(checky < 720){
        y++;
    }else{
        time.stop();
    }
    System.out.println(y);

}
//everything after this is what i call in the other method
    public Image getImage(){
    return flower;
}
public int getX(){
    return x;
}
public int getY(){
    return y;
}
    }

Now this is my drawing code...

    public void paintComponent(java.awt.Graphics g){
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    g2d.drawImage(rf.getImage(), rf.getX(), rf.getY(), null);// rf is what i called the method
    g2d.drawImage(sc.getImage(), sc.getX(), sc.getY(), null);//this is the basket that you control
}

Also a weird thing is when i make pressing a button call the method it works but not when the thread runs it...

删除双斜杠。

 ImageIcon i = new ImageIcon("graphics/flowers/red_flower.png");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM