Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling in the data from the mouse that is missing in java

I have a simple paint program and im trying to convert what is on the screen to a 2d array. In the mouseDragged method in java swing you can get the points at which the mouse is dragged to but it wont sample position enough times to get all the points you have drawn.

public void mouseDragged(MouseEvent me) {
    p.lineTo(me.getX(), me.getY());
    x=me.getX();
    y=me.getY();
    lines[me.getX()][me.getY()]=1;
    repaint();
}

In this I have the 2D array lines which has a 0 at every empty pixel and a 1 at every colored pixel. The issue is that when I print out the array I see that the mouse listener does not see all the points at which I had drawn on a canvas. It skips some points. So my question is how to connect these missing points that appear on the screen but not on the array.

for example, the program will print,

  • {0,0,0,0,1,1,1,0,1,1,0,0,0}
  • {0,0,0,0,0,0,0,0,0,0,0,1,1}

what im asking is that if there is a good algorithm to fill in the zeroes that should be ones

I have a highly edited version of the code at http://wphooper.com/java/tutorial/source/Graphics/html/simplermouseinteraction/Drawing.php

like image 522
user3470876 Avatar asked Dec 30 '25 21:12

user3470876


1 Answers

Here is an example of linear interpolation in a matrix:

int x, y;

public void mousePressed(MouseEvent e) {
    x = e.getX();
    y = e.getY();
}

public void mouseDragged(MouseEvent e) {
    int dx = e.getX()-x,
        dy = e.getY()-y;
    double a;

    //the condition is for accuracy in vertical drags
    if (Math.abs(dx) >= Math.abs(dy)) {
        a = dy/((double) dx);

        for (int i = 0; Math.abs(i) < Math.abs(dx); i += Math.signum(dx)) {
            lines[x+i][(int) (y+i*a)] = 1;
        }
    } else {
        a = dx/((double) dy);

        for (int i = 0; Math.abs(i) < Math.abs(dy); i += Math.signum(dy)) {
            lines[(int) (x+i*a)][y+i] = 1;
        }
    }

    x = e.getX();
    y = e.getY();
    repaint();
}

I have tested it and it draws a continuous solid line.

like image 62
Ron C Avatar answered Jan 01 '26 10:01

Ron C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!