noVac noVac - 1 month ago 13
Java Question

Java paint program. Issues with frame area mouse press

Having issues with trying to select a color by clicking within a certain area.
When clicking in the area it sometimes does not respond to the click and when selecting a different color it will repeat previous and current color.

@Override
public void mousePressed(MouseEvent e) {
/*
* Selecting color
*/
if(e.getX()>0 && e.getX()<(cwidth) && e.getY()>1 && e.getY()<panelHeight){
c=Color.BLACK;
System.out.println("BLACK");

}
if(e.getX()>(cwidth) && x1< (cwidth*2) && e.getY()>1 && e.getY()<panelHeight){
c=Color.RED;
System.out.println("RED");
}
if(e.getX()>(cwidth*2) && x1< (cwidth*3) && e.getY()>1 && e.getY()< panelHeight){
c=Color.GREEN;
System.out.println("GREEN");

}
if(e.getX()>(cwidth*3) && x1< (cwidth*4) && e.getY()>1 && e.getY()<panelHeight){
c=Color.BLUE;
System.out.println("BLUE");

}


How would I fix this issue? I switched to using class level variables to calculate cell width to eliminate careless errors. Debug color message in console makes no sense why it wouldn't switch to the new color when the mouse is pressed instead of waiting for me to either double click or click on a different color.

Link to the full PaintPanel.java source code:

PaintPanel.java - http://pastebin.com/7pay4Paz

Answer

you need to use if-else:

@Override
public void mouseClicked(MouseEvent e) {
    /*
     * Selecting color
     */
    if(e.getX()>0 && e.getX()=<(cwidth)){
        c=Color.BLACK;
        System.out.println("BLACK");

    }
    else if(e.getX()>(cwidth) && x1=< (cwidth*2) ){
        c=Color.RED;
        System.out.println("RED");
    }
    else if(e.getX()>(cwidth*2) && x1=< (cwidth*3)){
        c=Color.GREEN;
        System.out.println("GREEN");

    }
    else if(e.getX()>(cwidth*3) && x1=< (cwidth*4)){
        c=Color.BLUE;
        System.out.println("BLUE");

    }

This way, when one of the conditions is true, the program will not check if the rest are true.