简体   繁体   中英

Thread won't start

I am attempting to move an star image diagonally across. I am using a Thread to try and achieve this. The program compiles and the image is displayed, however the star won't move at all. I dont think the thread started properly.

Help would be greatly appreciated

drawing class (Board):

    //define host package
package star;

//import awt and swing drawing packages
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;

//jpanel and other javax classes
import javax.swing.JPanel;
import javax.swing.ImageIcon;

//main board class
public class Board extends JPanel implements Runnable 
{
    //constructor
    Image star; //star image to hold image returned from directory
    int x, y; //co ordinates for translation of star image
    //delay constant
    private final int DELAY = 50;
    private Thread animator;

    public Board()
    {
       //set the background colour to black
        setBackground(Color.black);

        //image directory
        ImageIcon ii = new ImageIcon(this.getClass().getResource("star.png"));
        //retrieve image from directory
        star = ii.getImage();

        //paint in memory then screen to improve
        setDoubleBuffered(true);

        //set star co ords variables
        x = y = 10;
    }

    //initialize thread
    void AddNotify()
    {
        super.addNotify();
        //run method in this class
        animator = new Thread(this);
        animator.start();
    }

    //jpanel paintComponent() with abstract graphics object
    @Override public void paintComponent(Graphics comp)
    {
        //repaint screen due to animation
        super.paintComponent(comp);
        Graphics2D comp2d = (Graphics2D) comp;
        //draw the star
        //class should be notified of drawing
        comp2d.drawImage(star, x, y, this);

        //sync for linux systems
        Toolkit.getDefaultToolkit().sync();
        comp.dispose();
    }

    //set the coordinates for the star image
    public void cycle()
    {
        //move star
        x += 1;
        y += 1;

        //if top corner goes out of range
        if (y > 240)
        {
            x = -45;
            y = -45;
        }
        System.out.println("x: " + x + "y: " + y);
    }

    //action performed method. Event parameter from the timer
    public void run()
    {
       //beforeTime, timeDiff and sleep variables
       //long = 2 x integer
       long beforeTime, timeDiff, sleep;

       beforeTime = System.currentTimeMillis();

       //infinite loop
       while (true)
       {
           //cycle and add notify methods
           cycle();
           //call the paintComponent method
           repaint();

           //compute system time
           timeDiff = System.currentTimeMillis() - beforeTime;
           /*subtracting from delay keeps lag from cycle() & AddNotify() 
             methods unoticable.
             timeDiff will change with each loop cycle
           */ 
           sleep = DELAY - timeDiff;

            //compensate for a timeDiff > 50
            if (sleep < 0)
            {
                sleep = 2;
            }

           //sleep thread in exception
           try
           {
               Thread.sleep(sleep);
           }
           catch (InterruptedException ie)
           {
               System.out.println("Thread could not sleep: " + ie.getMessage());
           }

           //reset beforeTime time
           beforeTime = System.currentTimeMillis();
       }
    }
}

main java frame class:

    //import jframe
import javax.swing.JFrame;

//main class
public class Star extends JFrame
{
    //constructor
    public Star()
    {
        //title, resize, size, location etc.
        add(new Board2());
        setTitle("Star animation");
        setSize(240, 280);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }

    //class instance
    public static void main(String[] arguements)
    {
       new Star();
    }
}

Happy to clarify on request.

You're never calling AddNotify method, which is where you start your thread. I'm guessing you have a typo, and you meant addNotify instead (notice the lower case).

When overriding methods, it's useful to add @Override tag, as compiler will complain if the method you're overriding does not exists.

@Override
void addNotify() {
    super.addNotify();
    //run method in this class
    animator = new Thread(this);
    animator.start();
}

It seems your Thread start call is not invoked anywhere in your code execution. You are starting the thread in AddNotify method but that method is not called.

Also your code has a compilation problem on this line:

    add(new Board2());

there is no class Board2 , rather your class name is Board . I expect it is just an error while pasting the code here.

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