dio dio - 6 months ago 16
Java Question

Conditional statement using accessor methods in Java

my

_holder.getColor()
is supposed to return the color RED by default and these conditional statements are not working. I think I have the syntax wrong.

Basically I want to be able to highlight a paintswatch when I click on it, and if the swatch color is the same as the one in
ColorHolder
, I want it to deselect the swatch.

import wheels.users.*;
import java.awt.Color;
import java.awt.event.MouseEvent;

public class PaintSwatch extends Ellipse
{
private ColorHolder _holder;
public int _i;

public PaintSwatch(Color c,ColorHolder holder){
super(c);
_holder = holder;
_i = 1;
}

public void mouseClicked(MouseEvent e){
if (_holder.getColor() != super.getColor()){
super.setFrameColor(Color.BLACK);
super.setFrameThickness(3);
_holder.setColor(super.getColor());
}

if (_holder.getColor() == super.getColor()){
super.setFrameThickness(10);
super.setFrameColor(Color.WHITE);
_holder.setColor(Color.RED);
}
}
}


Here is my ColorHolder Class:

import java.awt.Color;

public class ColorHolder implements Colorable
{
private Color _currentColor;

public ColorHolder()
{
_currentColor = Color.RED;
}

public Color getColor(){
return _currentColor;
}

public void setColor(Color c){
_currentColor = c;
}
}

Answer

Apart from using equals you should also use an if else instead of two distinct ifs :

if (_holder.getColor() != super.getColor()) {
   ...
   _holder.setColor(super.getColor());
}

if (_holder.getColor() == super.getColor()) { 
   ...
}

Note that the second if condition will always evaluate to true - if the holder's color is not equal to super's color, it will be set in the first if condition.

if (_holder.getColor().equals(super.getColor())) {
   ... do sth
} else {
   ... do sth else
}

Also make sure that either the holder and super do not return null as color or check it explicitly.