1 3 package org.faceless.graph2; 4 5 import java.text.NumberFormat ; 6 import java.util.Locale ; 7 8 13 public class NumericAxis extends Axis 14 { 15 private NumberFormat f; 16 private final int density; 17 private boolean stretch, integer; 18 19 22 public static final NumericAxis getIntegerAxis() 23 { 24 return new NumericAxis(NumberFormat.getIntegerInstance()); 25 } 26 27 30 public static final NumericAxis getFloatingPointAxis() 31 { 32 return new NumericAxis(NumberFormat.getNumberInstance()); 33 } 34 35 40 public static final NumericAxis getCurrencyAxis(Locale locale) 41 { 42 return new NumericAxis(NumberFormat.getCurrencyInstance(locale==null ? Locale.getDefault() : locale)); 43 } 44 45 49 public NumericAxis(NumberFormat format) 50 { 51 this(format, DENSITY_NORMAL); 52 } 53 54 59 public NumericAxis(NumberFormat format, int density) 60 { 61 setFormat(format); 62 this.density = density; 63 stretch = true; 64 } 65 66 void setFormat(NumberFormat format) 67 { 68 f=format; 69 this.integer = format(1).equals(format(1.4)); 70 } 71 72 boolean isInteger() { return integer; } 73 74 public String format(double in) 75 { 76 if (in==-0.0) in=0; 77 synchronized(f) { 78 return f.format(in); 79 } 80 } 81 82 90 public void setStretchEnds(boolean stretch) 91 { 92 this.stretch = stretch; 93 } 94 95 104 public double[] steps(double min, double max) 105 { 106 double[] out; 107 double ss = stepSize(min, max); 108 if (integer) ss = Math.ceil(ss); 109 110 if (ss==0) { 111 out = new double[1]; 112 out[0] = min; 113 } else { 114 double newmin = Math.floor(min/ss)*ss; 115 double newmax = Math.ceil(max/ss)*ss; 116 if (!stretch) { 117 if (newmin+ss-min < min-newmin) newmin+=ss; 118 if (max-newmax+ss < newmax-max) newmax-=ss; 119 } 120 int num = (int)Math.floor((newmax+(ss/5)-newmin)/ss); 121 out = new double[num+1]; 122 for (int i=0;i<out.length;i++) { 123 out[i] = newmin+(ss*i); 124 if (integer) out[i] = Math.floor(out[i]); 125 } 126 if (!stretch) { 127 out[0] = min; 128 out[out.length-1] = max; 129 } 130 } 131 return out; 132 } 133 134 private static final double diffs[] = { 0, 1, 2, 5, 5, 5, 5, 5, 10, 10, 10 }; 135 private double stepSize(double min, double max) 136 { 137 double diff = Math.abs(max-min); 138 if (diff==0) return 0; 139 diff/=density; 140 141 double mul=1; 142 while (diff<1) { 143 mul *= 10; 144 diff *= 10; 145 } 146 147 while (diff>10) { 148 mul /= 10; 149 diff /= 10; 150 } 151 152 diff = Math.round(diff); 153 diff = diffs[(int)diff]/mul; 154 155 return diff; 156 } 157 } 158 | Popular Tags |