Search code examples
javacanvaspointgraphics2d

Drawing SWT Point with different colors according to their positions ((x,y) coordinates) on canvas


I am trying to draw points on canvas with different colors. Basically, Current point in Blue, Point drawn before current point in Green and Point draw after current point in red. Please see the code

private void setElemColor(GC g, int pos) {
    int currentPoint = messtisch.getPointPos(); //current point, number
    if (pos > currentPoint) {
        g.setForeground(cRed);
    } else if (pos == currentPoint) {
        g.setForeground(cBlue);
    } else if (pos < currentPoint) {
        g.setForeground(cGreen);
    }
} 

to increase the comprehension. This works perfect. But I am trying to use Point in place of Int to do same and not getting logic right. As in

private void setPointColor(GC g, Point cpoint) {
    if (cpoint.equals(currentPoint)) { // the current point itself
        g.setForeground(cBlue);
    } else if (!cpoint.equals(currentPoint)) {
        if (cpoint.x > currentPoint.x || cpoint.y > currentPoint.y) {
            g.setForeground(cRed);
        } else {
            g.setForeground(cGreen);
        }      
    }
}

Please help me regarding.


Solution

  • I did it by using a new ArrayList and saving points to that are already been currentPoint. And then drawing them in Green color as old points. Here is my code sample.

    private ArrayList<Point> oldpoints = new ArrayList<Point>();  
    
    private void setPointColor(GC g, Point cpoint) {
        if (oldpoints.contains(cpoint)) {
            g.setForeground(cGreen);
        } else if (!oldpoints.contains(cpoint)) {
            g.setForeground(cRed);
        }
    
        if (cpoint.equals(currentPoint)) {
             g.setForeground(cBlue);
             oldpoints.add(cpoint);
        } 
    }
    

    Please suggest other medhod, as this one is not efficient and logicful. Thanking you in advance.