Offset.java

  1. package swingtree.style;

  2. import com.google.errorprone.annotations.Immutable;

  3. import java.util.Objects;

  4. /**
  5.  *  An immutable value object that represents an offset from a position
  6.  *  in the form of an x and y offset or lack thereof (0, 0).
  7.  */
  8. @Immutable
  9. final class Offset
  10. {
  11.     private static final Offset _NONE = new Offset(0, 0);

  12.     public static Offset none() { return _NONE; }

  13.     public static Offset of( float x, float y ) {
  14.         if ( x == 0 && y == 0 )
  15.             return _NONE;

  16.         return new Offset(x, y);
  17.     }

  18.     public static Offset of( double x, double y ) {
  19.         return Offset.of((float) x, (float) y);
  20.     }


  21.     private final float _x;
  22.     private final float _y;


  23.     private Offset( float x, float y ) {
  24.         _x = x;
  25.         _y = y;
  26.     }

  27.     float x() { return _x; }

  28.     float y() { return _y; }

  29.     Offset withX( float x ) { return Offset.of(x, _y); }

  30.     Offset withY( float y ) { return Offset.of(_x, y); }

  31.     Offset scale( double scaleFactor ) {
  32.         return Offset.of((int) Math.round(_x * scaleFactor), (int) Math.round(_y * scaleFactor));
  33.     }

  34.     @Override
  35.     public String toString() {
  36.         return this.getClass().getSimpleName()+"[" +
  37.                     "x=" + _toString(_x) + ", "+
  38.                     "y=" + _toString(_y) +
  39.                 "]";
  40.     }

  41.     private static String _toString( float value ) {
  42.         return String.valueOf(value).replace(".0", "");
  43.     }

  44.     @Override
  45.     public int hashCode() {
  46.         return Objects.hash(_x, _y);
  47.     }

  48.     @Override
  49.     public boolean equals( Object obj ) {
  50.         if ( obj == null ) return false;
  51.         if ( obj == this ) return true;
  52.         if ( obj.getClass() != getClass() ) return false;
  53.         Offset rhs = (Offset) obj;
  54.         return _x == rhs._x && _y == rhs._y;
  55.     }
  56. }