tags:

views:

27

answers:

1

I was trying to create a 2D Animation in Java of a moving line on Panel(A line moving from one point to another in the Panel). I hope its possible. Here's the code I used.

private void movingline(int length) throws InterruptedException {
        for(int i = 0; i + length < width; i++){
            for(int j = 0; j + length < height; j++){
                 eraseline(); 
                 drawLine(Color.cyan, i, j, i+length, j+length);
                 erase = true;
            }
        }
    }

    private void eraseline() {
        if(erase){
            fillCanvas(Color.BLUE);
        }
    }

On running the code, the Panel doesn't show up.

Here's the code to draw the line.

 public void drawLine(Color c, int x1, int y1, int x2, int y2) {
        int pix = c.getRGB();
        int dx = x2 - x1;
        int dy = y2 - y1;
        canvas.setRGB(x1, y1, pix);
        if (dx != 0) {
            float m = (float) dy / (float) dx;
            float b = y1 - m*x1;
            dx = (x2 > x1) ? 1 : -1;
            while (x1 != x2) {
                x1 += dx;
                y1 = Math.round(m*x1 + b);
                canvas.setRGB(x1, y1, pix);
            }
        }
        repaint();
    }

On running the code the Panel doesn't show up with the moving line. Any help would be much appreciated.

+1  A: 

I think the biggest problem is that you're trying to change the appearance of the GUI from (I'm guessing) a Thread that's not the Event Dispatching Thread.

The solution is to wrap the activity (specifically, the calls to eraseLine and drawLine) in a Runnable and call that Runnable using SwingUtilities.invokeAndWait().


EDIT: Java's graphics components don't really let you manipulate the canvas yourself. Only the components themselves do any drawing, and then only when called on to paint themselves. Directly drawing on the canvas, even if you could get it to work, would work badly because you'd be interfering with what the component does.

Rather than go into a lot more explanation, I've gone and implemented what I think is the "proper" way to do this.

http://pastebin.com/etfmKbjj

The coding's commented where necessary, I hope it gives you some ideas. For more background, read the official tutorials on Swing and Graphics.

Carl Smotricz
I didnt quite get you. The function movingline() is invoked from the constructor of the class.
razor35
There's the problem: Your class' constructor is most likely called by `main()`, and that's the main thread. Drawing must happen in the Event Dispatch Thread, which is started internally by Java when you have Swing (or AWT) components. To work correctly, your drawing should be done in the `paint()` method of the panel. You can't (or at least shouldn't) call `paint()` directly, though. All you can do from the outside is set some variables to control how it does its work.
Carl Smotricz
Updated my answer with sample code and some explanation.
Carl Smotricz