java.util.Formatter Java Examples

The following examples show how to use java.util.Formatter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TextHistogram.java    From testability-explorer with Apache License 2.0 7 votes vote down vote up
public String[] graph(float... values) {
  String[] rows = new String[height + 1];
  if (max == -1) {
    max = (int) Math.ceil(maxFloat(values));
  }
  int bucketWidth = (int)Math.ceil((float)(max - min) / height);
  int[] counts = count(bucketWidth, values);
  int maxCount = max(counts);
  StringBuilder out = new StringBuilder();
  Formatter formatter = new Formatter(out);
  formatter.format("%8d %" + width + "d", 0, maxCount);
  rows[0] = out.toString();
  for (int i = 0; i < counts.length; i++) {
    out.setLength(0);
    int bucketId = (int) (min + bucketWidth * i + bucketWidth / 2f);
    PieGraph pieGraph = new PieGraph(width, new CharMarker(marker.get(i, bucketId), ' '));
    String bar = pieGraph.render(counts[i], maxCount - counts[i]);
    formatter.format("%6d |%s:%6d", bucketId, bar, counts[i]);
    rows[i + 1] = out.toString();
  }
  return rows;
}
 
Example #2
Source File: TestN3iospNewProblem.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void compareWithBuilder(String filename) throws Exception {
  logger.info("TestBuilders on {}%n", filename);
  SPFactory.setServiceProvider("ucar.nc2.iosp.netcdf3.N3raf");
  try (NetcdfFile org = NetcdfFile.open(filename)) {
    SPFactory.setServiceProvider("ucar.nc2.internal.iosp.netcdf3.N3iospNew");
    try (NetcdfFile withBuilder = NetcdfFile.open(filename)) {
      Formatter f = new Formatter();
      CompareNetcdf2 compare = new CompareNetcdf2(f, false, false, true);
      if (!compare.compare(org, withBuilder)) {
        System.out.printf("Compare %s%n%s%n", filename, f);
        fail();
      }
    }
  } finally {
    SPFactory.setServiceProvider("ucar.nc2.iosp.netcdf3.N3raf");
  }
}
 
Example #3
Source File: PayloadExceptionLogging.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
public synchronized void logAndClear() {

        if (payloadIdMissingMessagesMap.isEmpty()) {
            return;
        }

        final StringBuilder stringBuilder = new StringBuilder();
        final Formatter formatter = new Formatter(stringBuilder);

        formatter.format("%n%1$31s%n%n", "MISSING PAYLOADS");
        formatter.format("%1$19s | %2$8s | %3$47s %n", "payloadId", "retained", "topic");
        formatter.format("%1$s%n", bigLine);
        for (final Map.Entry<Long, MissingMessageInformation> entry : payloadIdMissingMessagesMap.entrySet()) {
            final MissingMessageInformation missingMessage = entry.getValue();
            formatter.format("%1$19d | %2$8b | %3$47s %n", missingMessage.getPayloadId(), missingMessage.isRetained(), missingMessage.getTopic());
            formatter.format("%n%1$s%n", smallLine);
        }

        formatter.flush();
        migrationLog.warn(stringBuilder.toString());
        payloadIdMissingMessagesMap.clear();
    }
 
Example #4
Source File: TFormatter.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(final Formatter f, final Object aValueToWrite, final Appendable aOut) throws IOException {
    if (aValueToWrite == null) {
        if ((flags & FormattableFlags.UPPERCASE) > 0) {
            aOut.append("NULL");
        } else {
            aOut.append("null");
        }
    } else if (aValueToWrite instanceof Boolean) {
        if ((flags & FormattableFlags.UPPERCASE) > 0) {
            aOut.append(String.valueOf(((Boolean) aValueToWrite).booleanValue()).toUpperCase());
        } else {
            aOut.append(String.valueOf(((Boolean) aValueToWrite).booleanValue()));
        }
    } else {
        if ((flags & FormattableFlags.UPPERCASE) > 0) {
            aOut.append("true");
        } else {
            aOut.append("true");
        }
    }
}
 
Example #5
Source File: LetvUtils.java    From letv with Apache License 2.0 6 votes vote down vote up
public static String getNumberTime2(long time_second) {
    Formatter formatter = new Formatter(null, Locale.getDefault());
    if (time_second < 0) {
        time_second = 0;
    }
    try {
        String formatter2;
        long seconds = time_second % 60;
        if (time_second / 60 > 99) {
            formatter2 = formatter.format("%03d:%02d", new Object[]{Long.valueOf(time_second / 60), Long.valueOf(seconds)}).toString();
        } else {
            formatter2 = formatter.format("%02d:%02d", new Object[]{Long.valueOf(time_second / 60), Long.valueOf(seconds)}).toString();
            formatter.close();
        }
        return formatter2;
    } finally {
        formatter.close();
    }
}
 
Example #6
Source File: BufrMessageViewer.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void readData(Formatter f) {
  List<MessageBean> beans = messageTable.getBeans();
  int count = 0;
  try {
    for (MessageBean bean : beans) {
      bean.read();
      count++;
    }
    f.format("Read %d messages", count);

  } catch (Exception e) {
    StringWriter sw = new StringWriter(10000);
    e.printStackTrace(new PrintWriter(sw));
    f.format("%s", sw.toString());
  }
}
 
Example #7
Source File: ResultsCommand.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * Write the columns as fixed width text to the output.
 *
 * @param out Output stream.
 * @param columns Columns
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void writeColumns(OutputStream out,
                                 List<List<String>> columns) throws IOException {
    // Create format using the column widths
    final String format = createTextFormatFromColumnWidths(columns);

    // Output
    try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
         Formatter formatter = new Formatter(output)) {
        final int rows = columns.get(0).size();
        final Object[] args = new Object[columns.size()];
        for (int row = 0; row < rows; row++) {
            for (int i = 0; i < args.length; i++) {
                args[i] = columns.get(i).get(row);
            }
            formatter.format(format, args);
        }
    }
}
 
Example #8
Source File: WrapperExecutor.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private URI readDistroUrlDeprecatedWay() throws URISyntaxException {
    String distroUrl = null;
    try {
        distroUrl = getProperty("urlRoot") + "/"
                + getProperty("distributionName") + "-"
                + getProperty("distributionVersion") + "-"
                + getProperty("distributionClassifier") + ".zip";
        Formatter formatter = new Formatter();
        formatter.format("Wrapper properties file '%s' contains deprecated entries 'urlRoot', 'distributionName', 'distributionVersion' and 'distributionClassifier'. These will be removed soon. Please use '%s' instead.%n", propertiesFile, DISTRIBUTION_URL_PROPERTY);
        warningOutput.append(formatter.toString());
    } catch (Exception e) {
        //even the deprecated properties are not provided, report error:
        reportMissingProperty(DISTRIBUTION_URL_PROPERTY);
    }
    return new URI(distroUrl);
}
 
Example #9
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("allPools")
void disposeLaterIsLazy(Function<PoolBuilder<Formatter, ?>, AbstractPool<Formatter>> configAdjuster) {
	Formatter uniqueElement = new Formatter();

	PoolBuilder<Formatter, ?> builder = PoolBuilder
			.from(Mono.just(uniqueElement))
			.sizeBetween(1, 1)
			.evictionPredicate((poolable, metadata) -> true);
	AbstractPool<Formatter> pool = configAdjuster.apply(builder);
	pool.warmup().block();

	Mono<Void> disposeMono = pool.disposeLater();
	Mono<Void> disposeMono2 = pool.disposeLater();

	assertThat(disposeMono)
			.isNotSameAs(disposeMono2);

	assertThatCode(uniqueElement::flush)
			.doesNotThrowAnyException();
}
 
Example #10
Source File: AppendableLogRecord.java    From buck with Apache License 2.0 6 votes vote down vote up
public void appendFormattedMessage(StringBuilder sb) {
  // Unfortunately, there's no public API to reset a Formatter's
  // Appendable. If this proves to be a perf issue, we can do
  // runtime introspection to access the private Formatter.init()
  // API to replace the Appendable.

  try (Formatter f = new Formatter(sb, Locale.US)) {
    f.format(getMessage(), getParameters());
  } catch (IllegalFormatException e) {
    sb.append("Invalid format string: ");
    sb.append(displayLevel);
    sb.append(" '");
    sb.append(getMessage());
    sb.append("' ");
    Object[] params = getParameters();
    if (params == null) {
      params = new Object[0];
    }
    sb.append(Arrays.asList(params));
  } catch (ConcurrentModificationException originalException) {
    // This way we may be at least able to figure out where offending log was created.
    throw new ConcurrentModificationException(
        "Concurrent modification when logging for message " + getMessage(), originalException);
  }
}
 
Example #11
Source File: FormatterTest.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Test
public void testUselessWidthAndPrecision() {
    final Formattable f = new Formattable() {
        @Override
        public void formatTo(final Formatter formatter, final int flags, final int width, final int precision) {
            final StringBuilder sb = new StringBuilder();
            sb.append(flags);
            sb.append(":");
            sb.append(width);
            sb.append(":");
            sb.append(precision);
            formatter.format("%s", sb);
        }
    };
    final String result = String.format("%10.3s", f);
    System.out.println(result);
    Assert.assertEquals("0:10:3", result);
}
 
Example #12
Source File: AuthenticatedFilter.java    From mblog with GNU General Public License v3.0 6 votes vote down vote up
@Override
  protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
          throws ServletException, IOException {

      Subject subject = SecurityUtils.getSubject();
      if (subject.isAuthenticated() || subject.isRemembered()) {
          chain.doFilter(request, response);
      } else {
          WebUtils.saveRequest(request);
          String path = WebUtils.getContextPath((HttpServletRequest) request);
          String url = loginUrl;
          if (StringUtils.isNotBlank(path) && path.length() > 1) {
              url = path + url;
          }

          if (isAjaxRequest((HttpServletRequest) request)) {
              response.setContentType("application/json;charset=UTF-8");
              response.getWriter().print(JSON.toJSONString(Result.failure("您还没有登录!")));
          } else {
response.setContentType("text/html;charset=UTF-8");
              response.getWriter().write(new Formatter().format(JS, url).toString());
          }
      }
  }
 
Example #13
Source File: ArrayStructureBB.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static int showOffsets(StructureMembers members, Indent indent, Formatter f) {
  int offset = 0;
  for (StructureMembers.Member m : members.getMembers()) {
    f.format("%s%s offset=%d (%d %s = %d bytes)%n", indent, m.getName(), m.getDataParam(), m.getSize(),
        m.getDataType(), m.getSizeBytes());

    if (m.getStructureMembers() != null) {
      indent.incr();
      StructureMembers nested = m.getStructureMembers();
      f.format("%n%s%s == %d bytes%n", indent, nested.getName(), nested.getStructureSize());
      showOffsets(nested, indent, f);
      indent.decr();
    }
  }
  return offset;
}
 
Example #14
Source File: MessageInterpolator.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * EL式を評価する。
 * @param expression EL式
 * @param values EL式中の変数。
 * @return 評価した式。
 * @throws ExpressionEvaluationException 
 */
protected String evaluateExpression(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
    
    final Map<String, Object> context = new LinkedHashMap<String, Object>();
    context.putAll(values);
    
    // フォーマッターの追加
    context.computeIfAbsent("formatter", key -> new Formatter());
    
    final String value = expressionLanguage.evaluate(expression, context).toString();
    if(logger.isTraceEnabled()) {
        logger.trace("evaluate expression language: expression='{}' ===> value='{}'", expression, value);
    }
    
    return value;
}
 
Example #15
Source File: Graal.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets a capability provided by the {@link GraalRuntime} instance available to the application.
 *
 * @throws UnsupportedOperationException if the capability is not available
 */
public static <T> T getRequiredCapability(Class<T> clazz) {
    T t = getRuntime().getCapability(clazz);
    if (t == null) {
        String javaHome = System.getProperty("java.home");
        String vmName = System.getProperty("java.vm.name");
        Formatter errorMessage = new Formatter();
        if (getRuntime().getClass() == InvalidGraalRuntime.class) {
            errorMessage.format("The VM does not support the Graal API.%n");
        } else {
            errorMessage.format("The VM does not expose required Graal capability %s.%n", clazz.getName());
        }
        errorMessage.format("Currently used Java home directory is %s.%n", javaHome);
        errorMessage.format("Currently used VM configuration is: %s", vmName);
        throw new UnsupportedOperationException(errorMessage.toString());
    }
    return t;
}
 
Example #16
Source File: Grib2Gds.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testHorizCoordSys(Formatter f) {
  GdsHorizCoordSys cs = makeHorizCoordSys();
  f.format("%s testProjection %s%n", getClass().getName(), cs.proj.getClass().getName());

  double endx = cs.startx + (getNx() - 1) * cs.dx;
  double endy = cs.starty + (getNy() - 1) * cs.dy;
  ProjectionPoint endPP = ProjectionPoint.create(endx, endy);
  f.format("   start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty));
  f.format("     end at proj coord= %s%n", endPP);

  LatLonPoint startLL = LatLonPoint.create(la1, lo1);
  LatLonPoint endLL = cs.proj.projToLatLon(endPP);

  f.format("  start at latlon= %s%n", startLL);
  f.format("    end at latlon= %s%n", endLL);
}
 
Example #17
Source File: HierarchicalClassifierTrainer.java    From OpenEphyra with GNU General Public License v2.0 6 votes vote down vote up
private String prettyPrintCM (Evaluation.Matrix matrix, String[] classes ) {
    double[][] values = matrix.values;
    String[] classAbb = new String[classes.length];
    StringBuilder res = new StringBuilder();
    Formatter formatter = new Formatter(res,Locale.US);
    int max = 0;
    for (int i = 0; i < classes.length; i++) {
        classAbb[i] = classes[i].replaceAll("\\B(.{1,2}).*?(.)\\b","$1$2");
        if (classAbb[i].length() > max) max = classAbb[i].length();
    }
    max++;
    String formatStr = "%-"+max+"s";
    formatter.format(formatStr,"");
    for (int i = 0; i < classes.length; i++) {
        formatter.format(formatStr,classAbb[i]);
    }
    res.append("\n\n");
    for (int i = 0; i < classes.length; i++ ) {
        formatter.format(formatStr,classAbb[i]);
        for (int j = 0; j < classes.length; j++) {
            formatter.format(formatStr,Double.toString(values[i][j]));
        }
        res.append("\n\n");
    }
    return res.toString();
}
 
Example #18
Source File: AbstractTCKTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility method to dump a byte array in a java syntax.
 * @param bytes and array of bytes
 * @return a string containing the bytes formatted in java syntax
 */
protected static String dumpSerialStream(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 5);
    Formatter fmt = new Formatter(sb);
    fmt.format("    byte[] bytes = {" );
    final int linelen = 10;
    for (int i = 0; i < bytes.length; i++) {
        if (i % linelen == 0) {
            fmt.format("%n        ");
        }
        fmt.format(" %3d,", bytes[i] & 0xff);
        if ((i % linelen) == (linelen-1) || i == bytes.length - 1) {
            fmt.format("  /*");
            int s = i / linelen * linelen;
            int k = i % linelen;
            for (int j = 0; j <= k && s + j < bytes.length; j++) {
                fmt.format(" %c", bytes[s + j] & 0xff);
            }
            fmt.format(" */");
        }
    }
    fmt.format("%n    };%n");
    return sb.toString();
}
 
Example #19
Source File: TestNc4IospReading.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean doCompare(String location, boolean showCompare, boolean showEach, boolean compareData)
    throws IOException {
  try (NetcdfFile ncfile = NetcdfFiles.open(location); NetcdfFile jni = openJni(location)) {
    jni.setLocation(location + " (jni)");
    // System.out.printf("Compare %s to %s%n", ncfile.getIosp().getClass().getName(),
    // jni.getIosp().getClass().getName());

    Formatter f = new Formatter();
    CompareNetcdf2 tc = new CompareNetcdf2(f, showCompare, showEach, compareData);
    boolean ok = tc.compare(ncfile, jni, new CompareNetcdf2.Netcdf4ObjectFilter());
    System.out.printf(" %s compare %s ok = %s%n", ok ? "" : "***", location, ok);
    if (!ok || (showCompare && showCompareResults))
      System.out.printf("%s%n=====================================%n", f);
    return ok;
  }
}
 
Example #20
Source File: JPackerExecuter.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
private String encode(String script) {
    JPackerWords words = new JPackerWords(script, encoding);

    Pattern wordsPattern = Pattern.compile("\\w+");
    Matcher wordsMatcher = wordsPattern.matcher(script);
    StringBuffer sb = new StringBuffer();
    while (wordsMatcher.find()) {
        JPackerWord tempWord = new JPackerWord(wordsMatcher.group());
        wordsMatcher.appendReplacement(sb, words.find(tempWord).getEncoded());
    }
    wordsMatcher.appendTail(sb);

    int ascii = Math.min(Math.max(words.getWords().size(), 2), encoding.getEncodingBase());

    String p = escape(sb.toString());
    String a = String.valueOf(ascii);
    String c = String.valueOf(words.getWords().size());
    String k = words.toString();
    String e = getEncode(ascii);
    String r = ascii > 10 ? "e(c)" : "c";

    return new Formatter().format(UNPACK, p, a, c, k, e, r).toString();
}
 
Example #21
Source File: DsgSubsetWriterTest.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static boolean compareNetCDFNew(File expectedResultFile, File actualResultFile) throws IOException {
  try (NetcdfFile expectedNcFile = NetcdfDatasets.openDataset(expectedResultFile.getAbsolutePath());
      NetcdfFile actualNcFile = NetcdfDatasets.openDataset(actualResultFile.getAbsolutePath())) {
    Formatter formatter = new Formatter();
    boolean contentsAreEqual = new CompareNetcdf2(formatter, false, false, true).compare(expectedNcFile, actualNcFile,
        new NcssNetcdfObjFilter());

    if (!contentsAreEqual) {
      System.err.println(formatter.toString());
    }

    return contentsAreEqual;
  }
}
 
Example #22
Source File: EmulatorConsole.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public synchronized String sendLocation(double longitude, double latitude, double elevation) {

        // need to make sure the string format uses dot and not comma
        Formatter formatter = new Formatter(Locale.US);
        try {
            formatter.format(COMMAND_GPS, longitude, latitude, elevation);

            return processCommand(formatter.toString());
        } finally {
            formatter.close();
        }
    }
 
Example #23
Source File: Hdf5NewObjectTable.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void showInfo(Formatter f) throws IOException {
  if (iosp == null) {
    return;
  }
  for (ObjectBean bean : objectTable.getBeans()) {
    bean.m.show(f);
  }
}
 
Example #24
Source File: DetectionResult.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  DetectionResultColumn rowIndicatorColumn = detectionResultColumns[0];
  if (rowIndicatorColumn == null) {
    rowIndicatorColumn = detectionResultColumns[barcodeColumnCount + 1];
  }
  Formatter formatter = new Formatter();
  for (int codewordsRow = 0; codewordsRow < rowIndicatorColumn.getCodewords().length; codewordsRow++) {
    formatter.format("CW %3d:", codewordsRow);
    for (int barcodeColumn = 0; barcodeColumn < barcodeColumnCount + 2; barcodeColumn++) {
      if (detectionResultColumns[barcodeColumn] == null) {
        formatter.format("    |   ");
        continue;
      }
      Codeword codeword = detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
      if (codeword == null) {
        formatter.format("    |   ");
        continue;
      }
      formatter.format(" %3d|%3d", codeword.getRowNumber(), codeword.getValue());
    }
    formatter.format("%n");
  }
  String result = formatter.toString();
  formatter.close();
  return result;
}
 
Example #25
Source File: StandardCategoryLabelGenerator.java    From orson-charts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates the label for one series in a category chart.
 * 
 * @param dataset  the dataset ({@code null} not permitted).
 * @param seriesKey  the key ({@code null} not permitted).
 * 
 * @return The label (never {@code null} for this implementation). 
 */
@Override
public String generateSeriesLabel(CategoryDataset3D<S, R, C> dataset, 
        S seriesKey) {
    Args.nullNotPermitted(dataset, "dataset");
    Args.nullNotPermitted(seriesKey, "seriesKey");
    Formatter formatter = new Formatter(new StringBuilder());
    int count = DataUtils.count(dataset, seriesKey);
    double total = DataUtils.total(dataset, seriesKey);
    formatter.format(this.template, seriesKey, count, total);
    String result = formatter.toString();
    formatter.close();
    return result;
}
 
Example #26
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** CDL representation of Netcdf header info, non strict */
@Override
public String toString() {
  Formatter f = new Formatter();
  writeCDL(f, new Indent(2), false);
  return f.toString();
}
 
Example #27
Source File: LockFreeLogManager.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Log a message
 * @param format Message format
 * @param params Message parameters
 */
public void log(String format, Object ... params) {
    int id = logCntr.getAndIncrement();
    try (Formatter formatter = new Formatter()) {
        records.get().put(id, formatter.format(format, params).toString());
    }
}
 
Example #28
Source File: StrictConflictResolver.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public <T extends ModuleRevisionResolveState> T select(Collection<? extends T> candidates) {
    Formatter formatter = new Formatter();
    formatter.format("A conflict was found between the following modules:");
    for (ModuleRevisionResolveState candidate : candidates) {
        formatter.format("%n - %s", candidate.getId());
    }
    throw new RuntimeException(formatter.toString());
}
 
Example #29
Source File: URatioCellRenderer.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param g
 */
@Override
public void paint ( Graphics g ) {
    if ( mePaint ) {
        g.setColor(ReduxConstants.ColorOfUranium );
        // } else {
        //     g.setColor(selection);
    }
    // g.fillRect(0, 0, getWidth()-1, getHeight()-1);

    super.paint( g );

    g.setColor( Color.black );
    g.setFont( new Font( "Monospaced", Font.BOLD, 11 ) );

    String data[] = this.getText().split( ":" );
    StringBuilder ratio = new StringBuilder();
    StringBuilder stdErr = new StringBuilder();

    Formatter ratioFormatter = new Formatter( ratio );
    Formatter stdErrFormatter = new Formatter( stdErr );

    try {
        ratioFormatter.format( "%9.4f", Double.valueOf( data[0].trim() ) );
        g.drawString( ratio.substring( 0 ),
                (int) g.getClipBounds().getWidth() - 70, 12 ); // hard-coded for now 2,12);
        stdErrFormatter.format( "%9.4f", Double.valueOf( data[1].trim() ) );
        g.drawString( stdErr.substring( 0 ),
                (int) g.getClipBounds().getWidth() - 70, 27 );//, 2,27);
    } catch (Exception e) {
        // april 2010 draw whatever is there, for LAGACY = "n/a"
        g.drawString( data[0].trim(),
                (int) g.getClipBounds().getWidth() - 35 - data[0].trim().length() / 2, 20 ); // hard-coded for now 2,12);
    }
}
 
Example #30
Source File: GridTable.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Row(GridDatatype gg) {
  this.gg = gg;
  Formatter f = new Formatter();
  for (Dimension dim : gg.getDimensions())
    f.format("%s ", dim.getShortName());
  dims = f.toString();
}