List of usage examples for java.awt Graphics2D setFont
public abstract void setFont(Font font);
From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java
private void renderRange(LongRange pRange, LongRange pStartRange, LongRange pArriveRange, boolean pIsStartRange, boolean pIsArriveRange, Graphics2D pG2D, TimeSpan pSpanForRange, HashMap<String, Object> pPopupInfo) { int rangeStart = 0; int rangeWidth = 0; if (pRange.overlapsRange(pStartRange)) { //start range rendering long startDelta = pStartRange.getMinimumLong(); rangeStart = Math.round((pRange.getMinimumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE); // int rangeEnd = Math.round((pRange.getMaximumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE); rangeWidth = Math//from w w w . j a va 2 s . co m .round((pRange.getMaximumLong() - pRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE); } else if (pRange.overlapsRange(pArriveRange)) { //end range rendering long startDelta = pStartRange.getMinimumLong(); rangeStart = Math.round((pRange.getMinimumLong() - startDelta) / DateUtils.MILLIS_PER_MINUTE); // int rangeEnd = Math.round((pRange.getMaximumLong() - arriveDelta) / DateUtils.MILLIS_PER_MINUTE); rangeWidth = Math .round((pRange.getMaximumLong() - pRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE); } //correct small widths if (rangeWidth == 0) { rangeWidth = 5; } long max = Math.round( (pArriveRange.getMaximumLong() - pStartRange.getMinimumLong()) / DateUtils.MILLIS_PER_MINUTE); if (rangeStart > max) { return; } SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); String labelString = ""; if (pSpanForRange != null) { labelString = pSpanForRange.toString(); } else { labelString = f.format(new Date(pRange.getMinimumLong())) + " bis " + f.format(new Date(pRange.getMaximumLong())); } Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(labelString, pG2D); if (pIsStartRange) { pG2D.setColor(Color.RED); pG2D.fillRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.BLACK); pG2D.drawRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.RED); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 14.0f)); pG2D.drawString(labelString, rangeStart, (int) labelBounds.getHeight()); } else if (pIsArriveRange) { pG2D.setColor(Color.GREEN.darker()); pG2D.fillRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.BLACK); pG2D.drawRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.GREEN.darker()); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 14.0f)); pG2D.drawString(labelString, rangeStart, (int) labelBounds.getHeight() + 40); } else { pG2D.fillRect(rangeStart, 20, rangeWidth, 20); pG2D.setColor(Color.BLACK); pG2D.drawRect(rangeStart, 20, rangeWidth, 20); Point loc = getMousePosition(); if (loc != null && new Rectangle(rangeStart, 20, rangeWidth, 20).contains(loc)) { pPopupInfo.put("popup.location", loc); pPopupInfo.put("popup.label", labelString); pPopupInfo.put("active.range", pRange); pPopupInfo.put("span.for.range", pSpanForRange); } } }
From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java
/** * Draws the label for one axis.//ww w .j av a 2s .c om * * @param g2 the graphics device. * @param plotArea the plot area * @param value the value of the label (ignored). * @param cat the category (zero-based index). * @param startAngle the starting angle. * @param extent the extent of the arc. */ protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value, int cat, double startAngle, double extent) { FontRenderContext frc = g2.getFontRenderContext(); String label = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { // if series are in rows, then the categories are the column keys label = this.labelGenerator.generateColumnLabel(this.dataset, cat); } else { // if series are in columns, then the categories are the row keys label = this.labelGenerator.generateRowLabel(this.dataset, cat); } Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc); LineMetrics lm = getLabelFont().getLineMetrics(label, frc); double ascent = lm.getAscent(); Point2D labelLocation = calculateLabelLocation(labelBounds, ascent, plotArea, startAngle); Composite saveComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.setPaint(getLabelPaint()); g2.setFont(getLabelFont()); g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY()); g2.setComposite(saveComposite); }
From source file:org.viafirma.util.QRCodeUtil.java
/** * Genera codigo de firma para impresin formado por el texto, el cdigo qr * del texto y un cdigo de barras con el cdigo de firma. * /*from w ww. j ava 2s. c o m*/ * @param text * @param codFirma * @return * @throws ExcepcionErrorInterno */ public byte[] generate(String text, String url, String textoQR, String codFirma) throws ExcepcionErrorInterno { // Comprobamos el tamao del texto. No recomendamos textos de mas de 120 // caracteres if (textoQR.length() > MAX_TEXT_SIZE) { log.warn("El tamao del texto '" + text + "' ha excedido el tamao mximo. " + text.length() + ">" + MAX_TEXT_SIZE); textoQR = textoQR.substring(textoQR.lastIndexOf(" ")); log.warn("El texto sera recortado: '" + textoQR + "'"); } // Generamos la sufperficie de dibujo BufferedImage imagenQR = new BufferedImage(ANCHO_ETIQUETA, ALTO_ETIQUETA, BufferedImage.TYPE_INT_RGB); Graphics2D g = imagenQR.createGraphics(); // El fondo es blanco g.setBackground(Color.WHITE); g.clearRect(0, 0, ANCHO_ETIQUETA, ALTO_ETIQUETA); g.setColor(Color.BLACK); g.setStroke(new BasicStroke(2f)); // Pintamos la caja de borde g.draw(new java.awt.Rectangle(MARGEN_CAJA, MARGEN_CAJA, ANCHO_ETIQUETA - MARGEN_CAJA * 2, ALTO_ETIQUETA - MARGEN_CAJA * 2)); g.draw(new java.awt.Rectangle(MARGEN_CAJA + 3, MARGEN_CAJA + 3, ANCHO_ETIQUETA - MARGEN_CAJA * 2 - 6, ALTO_ETIQUETA - MARGEN_CAJA * 2 - 6)); // Generamos el cdigo QR Qrcode x = new Qrcode(); x.setQrcodeErrorCorrect('L'); x.setQrcodeEncodeMode('B'); // Modo Binario byte[] d = textoQR.getBytes(); // Generamos el cdigo QR boolean[][] s = x.calQrcode(d); for (int i = 0; i < s.length; i++) { for (int j = 0; j < s.length; j++) { if (s[j][i]) { g.fillRect(j * SIZE_QR + MARGEN, i * SIZE_QR + MARGEN, SIZE_QR, SIZE_QR); } } } int marjenSeparador = MARGEN + SIZE_QR * s.length + MARGEN_CAJA; int marjenTexto = marjenSeparador + MARGEN_CAJA; // Linea de separacin entre el QR cdigo y el texto g.drawLine(marjenSeparador - 3, MARGEN_CAJA + 3, marjenSeparador - 3, ALTO_ETIQUETA - MARGEN_CAJA - 3); g.drawLine(marjenSeparador, MARGEN_CAJA + 3, marjenSeparador, ALTO_ETIQUETA - MARGEN_CAJA - 3); // Linea de separacin entre texto y cdigo de barras. int marjenCodigoBarras = MARGEN + MAX_ROWS * FONT_SIZE; // Pintamos una pequea linea de separacin g.drawLine(marjenSeparador, marjenCodigoBarras, ANCHO_ETIQUETA - MARGEN_CAJA - 3, marjenCodigoBarras); g.drawLine(marjenSeparador, marjenCodigoBarras - 3, ANCHO_ETIQUETA - MARGEN_CAJA - 3, marjenCodigoBarras - 3); // Escribimos el texto List<String> parrafos = split(text); g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE)); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (int i = 0; i < parrafos.size(); i++) { String linea = parrafos.get(i); // Pintamos la nueva linea de texto g.drawString(linea, marjenTexto, MARGEN + 3 + (FONT_SIZE * i + 1)); } g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE - 4)); // Pintamos el texto final de una sola lnea( Generalmente el MD5 ) //if(url.length()) if (!url.equals("")) { g.drawString("Custodia del documento: ", marjenTexto, marjenCodigoBarras - 10 * 2); g.drawString(url, marjenTexto, marjenCodigoBarras - 6); } marjenCodigoBarras += MARGEN_CAJA; // Generamos el cdigo de barras try { // int marjenCodigoBarras=MARGEN+MAX_ROWS*FONT_SIZE; BarcodeFactory.createCode39(codFirma, true).draw(g, marjenTexto, marjenCodigoBarras); } catch (Exception e1) { // TODO e1.printStackTrace(); } // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_OFF); // Finalizamos la superficie de dibujo g.dispose(); ByteArrayOutputStream out = new ByteArrayOutputStream(); // Generamos la imagen try { ImageIO.write(imagenQR, "png", out); // ImageIO.write(imagenQR, "png", new // FileOutputStream("/tmp/imagen.png")); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } return out.toByteArray(); }
From source file:savant.view.tracks.BAMTrackRenderer.java
/** * Render the individual bases on top of the read. Depending on the drawing * mode this can be either bases read or mismatches. *///from w ww.j a v a 2s. c o m private void renderBases(Graphics2D g2, GraphPaneAdapter gp, SAMRecord samRecord, int level, byte[] refSeq, Range range, double unitHeight) { ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME); boolean baseQualityEnabled = (Boolean) instructions.get(DrawingInstruction.BASE_QUALITY); boolean drawingAllBases = lastMode == DrawingMode.SEQUENCE || baseQualityEnabled; double unitWidth = gp.getUnitWidth(); int offset = gp.getOffset(); // Cutoffs to determine when not to draw double leftMostX = gp.transformXPos(range.getFrom()); double rightMostX = gp.transformXPos(range.getTo()) + unitWidth; int alignmentStart = samRecord.getAlignmentStart(); byte[] readBases = samRecord.getReadBases(); byte[] baseQualities = samRecord.getBaseQualities(); boolean sequenceSaved = readBases.length > 0; Cigar cigar = samRecord.getCigar(); // Absolute positions in the reference sequence and the read bases, set after each cigar operator is processed int sequenceCursor = alignmentStart; int readCursor = alignmentStart; List<Rectangle2D> insertions = new ArrayList<Rectangle2D>(); FontMetrics fm = g2.getFontMetrics(MISMATCH_FONT); Rectangle2D charRect = fm.getStringBounds("G", g2); boolean fontFits = charRect.getWidth() <= unitWidth && charRect.getHeight() <= unitHeight; if (fontFits) { g2.setFont(MISMATCH_FONT); } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (CigarElement cigarElement : cigar.getCigarElements()) { int operatorLength = cigarElement.getLength(); CigarOperator operator = cigarElement.getOperator(); Rectangle2D.Double opRect = null; double opStart = gp.transformXPos(sequenceCursor); double opWidth = operatorLength * unitWidth; // Cut off start and width so no drawing happens off-screen, must be done in the order w, then x, since w depends on first value of x double x2 = Math.min(rightMostX, opStart + opWidth); opStart = Math.max(leftMostX, opStart); opWidth = x2 - opStart; switch (operator) { case D: // Deletion if (opWidth > 0.0) { renderDeletion(g2, gp, opStart, level, operatorLength, unitHeight); } break; case I: // Insertion insertions.add(new Rectangle2D.Double(gp.transformXPos(sequenceCursor), gp.transformYPos(0) - ((level + 1) * unitHeight) - gp.getOffset(), unitWidth, unitHeight)); break; case M: // Match or mismatch case X: case EQ: // some SAM files do not contain the read bases if (sequenceSaved || operator == CigarOperator.X) { for (int i = 0; i < operatorLength; i++) { // indices into refSeq and readBases associated with this position in the cigar string int readIndex = readCursor - alignmentStart + i; boolean mismatched = false; if (operator == CigarOperator.X) { mismatched = true; } else { int refIndex = sequenceCursor + i - range.getFrom(); if (refIndex >= 0 && refSeq != null && refIndex < refSeq.length) { mismatched = refSeq[refIndex] != readBases[readIndex]; } } if (mismatched || drawingAllBases) { Color col; if ((mismatched && lastMode != DrawingMode.STANDARD) || lastMode == DrawingMode.SEQUENCE) { col = cs.getBaseColor((char) readBases[readIndex]); } else { col = cs.getColor(samRecord.getReadNegativeStrandFlag() ? ColourKey.REVERSE_STRAND : ColourKey.FORWARD_STRAND); } if (baseQualityEnabled && col != null) { col = new Color(col.getRed(), col.getGreen(), col.getBlue(), getConstrainedAlpha( (int) Math.round((baseQualities[readIndex] * 0.025) * 255))); } double xCoordinate = gp.transformXPos(sequenceCursor + i); double top = gp.transformYPos(0) - ((level + 1) * unitHeight) - offset; if (col != null) { opRect = new Rectangle2D.Double(xCoordinate, top, unitWidth, unitHeight); g2.setColor(col); g2.fill(opRect); } if (lastMode != DrawingMode.SEQUENCE && mismatched && fontFits) { // If it's a real mismatch, we want to draw the base letter (space permitting). g2.setColor(new Color(10, 10, 10)); String s = new String(readBases, readIndex, 1); charRect = fm.getStringBounds(s, g2); g2.drawString(s, (float) (xCoordinate + (unitWidth - charRect.getWidth()) * 0.5), (float) (top + fm.getAscent() + (unitHeight - charRect.getHeight()) * 0.5)); } } } } break; case N: // Skipped opRect = new Rectangle2D.Double(opStart, gp.transformYPos(0) - ((level + 1) * unitHeight) - offset, opWidth, unitHeight); g2.setColor(cs.getColor(ColourKey.SKIPPED)); g2.fill(opRect); break; default: // P - passing, H - hard clip, or S - soft clip break; } if (operator.consumesReadBases()) { readCursor += operatorLength; } if (operator.consumesReferenceBases()) { sequenceCursor += operatorLength; } } for (Rectangle2D ins : insertions) { drawInsertion(g2, ins.getX(), ins.getY(), ins.getWidth(), ins.getHeight()); } }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void drawInformationBox(Graphics2D g2, Activities activities, Rectangle2D rect, List<String> params, List<String> values, String totalParam, double totalValue, Color background_color, Color border_color) { final Font oldFont = g2.getFont(); final Font paramFont = oldFont; final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont); final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1); final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont); final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1); final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont); final int x = (int) rect.getX(); final int y = (int) rect.getY(); final int width = (int) rect.getWidth(); final int height = (int) rect.getHeight(); final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Composite oldComposite = g2.getComposite(); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(border_color);/*from w w w.ja v a 2s.co m*/ g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15); g2.setColor(background_color); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect(x, y, width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); final Date date = activities.getDate().getTime(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy"); final String dateString = simpleDateFormat.format(date); final int padding = 5; int yy = y + padding + dateFontMetrics.getAscent(); g2.setFont(dateFont); g2.setColor(COLOR_BLUE); g2.drawString(dateString, ((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x, yy); int index = 0; final int dateInfoHeightMargin = 5; final int infoTotalHeightMargin = 5; final int paramValueHeightMargin = 0; yy += dateFontMetrics.getDescent() + dateInfoHeightMargin + Math.max(paramFontMetrics.getAscent(), valueFontMetrics.getAscent()); for (String param : params) { final String value = values.get(index++); g2.setColor(Color.BLACK); g2.setFont(paramFont); g2.drawString(param + ":", padding + x, yy); g2.setFont(valueFont); g2.drawString(value, width - padding - valueFontMetrics.stringWidth(value) + x, yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()); } if (values.size() > 1) { yy -= paramValueHeightMargin; yy += infoTotalHeightMargin; if (totalValue > 0.0) { g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR); } else if (totalValue < 0.0) { g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR); } g2.setFont(paramFont); g2.drawString(totalParam + ":", padding + x, yy); g2.setFont(valueFont); final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); final String totalValueStr = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalValue); g2.drawString(totalValueStr, width - padding - valueFontMetrics.stringWidth(totalValueStr) + x, yy); } g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java
/** * Render the pie chart with the given height * /*from w w w . j a v a 2 s . c om*/ * @param height * The height of the resulting image * @return The pie chart rendered as an image */ public BufferedImage render(int height) { BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.scale(zoom, zoom); // fill background to white g2.setColor(Color.WHITE); g2.fill(new Rectangle(totalWidth, totalHeight)); // prepare render hints g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); // draw shadow image g2.drawImage(pieShadow.getImage(), 0, 0, pieShadow.getImageObserver()); double start = 0; List<Arc2D> pies = new ArrayList<>(); // pie segmente erzeugen und fuellen if (total == 0) { g2.setColor(BRIGHT_GRAY); g2.fillOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius); g2.setColor(Color.WHITE); g2.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius); } else { for (Segment s : segments) { double portionDegrees = s.getPortion() / total; Arc2D pie = paintPieSegment(g2, start, portionDegrees, s.getColor()); if (withSubSegments) { double smallRadius = radius * s.getSubSegmentRatio(); paintPieSegment(g2, start, portionDegrees, smallRadius, s.getColor().darker()); } start += portionDegrees; // portion degree jetzt noch als String (z.B. "17.3%" oder "20%" zusammenbauen) String p = String.format(Locale.ENGLISH, "%.1f", Math.rint(portionDegrees * 1000) / 10.0); p = removeSuffix(p, ".0"); // evtl. ".0" bei z.B. "25.0" abschneiden (-> "25") s.setPercent(p + "%"); pies.add(pie); } // weissen Rahmen um die pie segmente zeichen g2.setColor(Color.WHITE); for (Arc2D pie : pies) { g2.draw(pie); } } // Legende zeichnen renderLegend(g2); // "xx%" Label direkt auf die pie segmente zeichen g2.setColor(Color.WHITE); float fontSize = 32f; g2.setFont(NORMALFONT.deriveFont(fontSize).deriveFont(Font.BOLD)); start = 0; for (Segment s : segments) { if (s.getPortion() < 1E-6) { continue; // ignore segments with portions that are extremely small } double portionDegrees = s.getPortion() / total; double angle = start + portionDegrees / 2; // genau in der Mitte des Segments double xOffsetForCenteredTxt = 8 * s.getPercent().length(); // assume roughly 8px per char int x = (int) (centerX + 0.6 * radius * Math.sin(2 * Math.PI * angle) - xOffsetForCenteredTxt); int y = (int) (centerY - 0.6 * radius * Math.cos(2 * Math.PI * angle) + fontSize / 2); g2.drawString(s.getPercent(), x, y); start += portionDegrees; } return image; }
From source file:paquete.HollywoodUI.java
public void dibujarAristas() { Graphics2D g = grafico.createGraphics(); g.setFont(new Font("SansSerif", Font.BOLD, 11)); adyaTemp = new ArrayList<>(this.HollyUniverseGraph.getEdges()); for (Actor temp_actor : actoresArray) { for (Arista temp_arista : adyaTemp) { g.setColor(Color.BLACK); g.drawLine(temp_actor.getX(), temp_actor.getY(), temp_arista.getNext().getX(), temp_arista.getNext().getY()); int nx = (temp_actor.getX() + temp_arista.getNext().getX()) / 2; int ny = (temp_actor.getY() + temp_arista.getNext().getY()) / 2; g.setColor(Color.ORANGE); if (temp_arista.getRelacion().equals("Amistad")) { g.setColor(Color.BLUE); g.drawString(temp_arista.getRelacion() + "", nx + 10, ny - 3); } else if (temp_arista.getRelacion().equals("Noviazgo")) { g.setColor(Color.GREEN); g.drawString(temp_arista.getRelacion() + "", nx + 10, ny + 23); } else if (temp_arista.getRelacion().equals("Matrimonio")) { g.setColor(Color.RED); g.drawString(temp_arista.getRelacion() + "", nx - 15, ny - 5); } else if (temp_arista.getRelacion().equals("Familia")) { g.setColor(Color.YELLOW); g.drawString(temp_arista.getRelacion() + "", nx - 15, ny - 5); }/* w w w . jav a2s. c om*/ } } Image img; img = Toolkit.getDefaultToolkit().createImage(grafico.getSource()).getScaledInstance(800, 600, 0); label_grafico.setIcon(new ImageIcon(img)); }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void drawBusyBox(Graphics2D g2, JXLayer<? extends V> layer) { final Font oldFont = g2.getFont(); final Font font = oldFont; final FontMetrics fontMetrics = g2.getFontMetrics(font); // Not sure why. Draw GIF image on JXLayer, will cause endless setDirty // being triggered by system. //final Image image = ((ImageIcon)Icons.BUSY).getImage(); //final int imgWidth = Icons.BUSY.getIconWidth(); //final int imgHeight = Icons.BUSY.getIconHeight(); //final int imgMessageWidthMargin = 5; final int imgWidth = 0; final int imgHeight = 0; final int imgMessageWidthMargin = 0; final String message = MessagesBundle.getString("info_message_retrieving_latest_stock_price"); final int maxWidth = imgWidth + imgMessageWidthMargin + fontMetrics.stringWidth(message); final int maxHeight = Math.max(imgHeight, fontMetrics.getHeight()); final int padding = 5; final int width = maxWidth + (padding << 1); final int height = maxHeight + (padding << 1); final int x = (int) this.drawArea.getX() + (((int) this.drawArea.getWidth() - width) >> 1); final int y = (int) this.drawArea.getY() + (((int) this.drawArea.getHeight() - height) >> 1); final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Composite oldComposite = g2.getComposite(); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(COLOR_BORDER);/*from w ww.j av a 2 s. c om*/ g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15); g2.setColor(COLOR_BACKGROUND); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect(x, y, width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); //g2.drawImage(image, x + padding, y + ((height - imgHeight) >> 1), layer.getView()); g2.setFont(font); g2.setColor(COLOR_BLUE); int yy = y + ((height - fontMetrics.getHeight()) >> 1) + fontMetrics.getAscent(); g2.setFont(font); g2.setColor(COLOR_BLUE); g2.drawString(message, x + padding + imgWidth + imgMessageWidthMargin, yy); g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:org.earthtime.UPb_Redux.dateInterpretation.WeightedMeanGraphPanel.java
/** * * @param g2d//www .j a va 2 s . c o m */ public void paint(Graphics2D g2d) { // setup painting parameters String fractionSortOrder = "name"; //random, weight, date if (getWeightedMeanOptions().containsKey("fractionSortOrder")) { fractionSortOrder = getWeightedMeanOptions().get("fractionSortOrder"); } double rangeX = (getMaxX_Display() - getMinX_Display()); double rangeY = (getMaxY_Display() - getMinY_Display()); g2d.setClip(getLeftMargin(), getTopMargin(), getGraphWidth(), getGraphHeight()); RenderingHints rh = g2d.getRenderingHints(); rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); // walk the sampleDateInterpretations and produce graphs g2d.setPaint(Color.BLACK); g2d.setStroke(new BasicStroke(2.0f)); g2d.setFont(new Font("SansSerif", Font.BOLD, 10)); double barWidth = 15.0; double barGap = 10.0; double startSamX = 10.0; double saveStartSamX = 0.0; double samSpace = 3.0; for (int i = 0; i < selectedSampleDateModels.length; i++) { for (int j = 1; j < 9; j++) { if (selectedSampleDateModels[i][j] instanceof SampleDateModel) { final SampleDateModel SAM = ((SampleDateModel) selectedSampleDateModels[i][j]); double wMean = SAM.getValue().movePointLeft(6).doubleValue(); double wMeanOneSigma = SAM.getOneSigmaAbs().movePointLeft(6).doubleValue(); Path2D mean = new Path2D.Double(Path2D.WIND_NON_ZERO); // july 2008 // modified to show de-selected fractions as gray // this means a new special list of fractionIDs is created fromall non-rejected fractions // and each instance is tested for being included // should eventually refactor Vector<String> allFIDs = new Vector<String>(); for (String f : ((UPbReduxAliquot) SAM.getAliquot()).getAliquotFractionIDs()) { // test added for Sample-based wm if (SAM.fractionDateIsPositive(// ((UPbReduxAliquot) SAM.getAliquot()).getAliquotFractionByName(f))) { allFIDs.add(f); } } final int iFinal = i; if (fractionSortOrder.equalsIgnoreCase("weight")) { Collections.sort(allFIDs, new Comparator<String>() { public int compare(String fID1, String fID2) { double invertOneSigmaF1 = // 1.0 // / ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID1)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getOneSigmaAbs().movePointLeft(6).doubleValue(); double invertOneSigmaF2 = // 1.0 // / ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID2)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getOneSigmaAbs().movePointLeft(6).doubleValue(); return Double.compare(invertOneSigmaF2, invertOneSigmaF1); } }); } else if (fractionSortOrder.equalsIgnoreCase("date")) { Collections.sort(allFIDs, new Comparator<String>() { public int compare(String fID1, String fID2) { double dateF1 = // ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID1)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getValue().doubleValue(); double dateF2 = // ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID2)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getValue().doubleValue(); return Double.compare(dateF1, dateF2); } }); } else if ( /* ! isInRandomMode() &&*/fractionSortOrder.equalsIgnoreCase("random")) { Collections.shuffle(allFIDs, new Random()); } else if (fractionSortOrder.equalsIgnoreCase("name")) { // default to alphabetic by name //Collections.sort(allFIDs); // april 2010 give same lexigraphic ordering that UPbFractions get Collections.sort(allFIDs, new IntuitiveStringComparator<String>()); } else { // do nothing } double actualWidthX = (allFIDs.size()) * (barWidth + barGap);//; + barGap; // plot 2-sigma of mean mean.moveTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.closePath(); g2d.setColor(ReduxConstants.mySampleYellowColor); g2d.fill(mean); g2d.setPaint(Color.BLACK); // plot 1-sigma of mean mean.reset(); mean.moveTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.closePath(); g2d.setColor(ReduxConstants.ColorOfRedux); g2d.fill(mean); g2d.setPaint(Color.BLACK); // plot mean mean.reset(); mean.moveTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean, getMaxY_Display(), rangeY, graphHeight)); g2d.setStroke(new BasicStroke(1.0f)); g2d.draw(mean); g2d.setStroke(new BasicStroke(2.0f)); saveStartSamX = startSamX; // plot fraction bars double minPoint = 5000.0; double maxWeight = 0.0; double totalWeight = 0.0; int barNum = 0; for (String fID : allFIDs) { // the dateModel has an associated aliquot, but in sample mode, it is a // standin aliquot for the sample. to get the aliquot number for // use in coloring fractions, we need to query the fraction itself String aliquotName = sample.getAliquotNameByFractionID(fID); Color includedFillColor = new Color(0, 0, 0); if (sample.getSampleDateInterpretationGUISettings().getAliquotOptions().get(aliquotName) .containsKey("includedFillColor")) { String[] temp = // sample.getSampleDateInterpretationGUISettings().getAliquotOptions() .get(aliquotName).get("includedFillColor").split(","); includedFillColor = buildRGBColor(temp); } Fraction f = ((UPbReduxAliquot) selectedSampleDateModels[i][0]) .getAliquotFractionByName(fID); double date = f.//((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID).// getRadiogenicIsotopeDateByName(SAM.getDateName()).getValue().movePointLeft(6) .doubleValue(); double twoSigma = f.//((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID).// getRadiogenicIsotopeDateByName(SAM.getDateName()).getTwoSigmaAbs().movePointLeft(6) .doubleValue(); if ((date - twoSigma) < minPoint) { minPoint = (date - twoSigma); } double invertedOneSigma = // 1.0 // / f.//((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID).// getRadiogenicIsotopeDateByName(SAM.getDateName()).getOneSigmaAbs() .movePointLeft(6).doubleValue(); if (invertedOneSigma > maxWeight) { maxWeight = invertedOneSigma; } Path2D bar = new Path2D.Double(Path2D.WIND_NON_ZERO); bar.moveTo( (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.lineTo( (float) mapX( saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)) + barWidth, getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.lineTo( (float) mapX( saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)) + barWidth, getMinX_Display(), rangeX, graphWidth), (float) mapY(date - twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.lineTo( (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date - twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.closePath(); Composite originalComposite = g2d.getComposite(); if (SAM.getIncludedFractionIDsVector().contains(fID)) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f)); totalWeight += Math.pow(invertedOneSigma, 2.0); // april 2014 experiment if (f.getRgbColor() != 0) { includedFillColor = new Color(f.getRgbColor()); } } else { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); } g2d.setPaint(includedFillColor); g2d.draw(bar); //restore composite g2d.setComposite(originalComposite); g2d.setColor(Color.black); // label fraction at top g2d.rotate(-Math.PI / 4.0, (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); g2d.drawString( ((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID) .getFractionID(), (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth) + 15, (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); g2d.rotate(Math.PI / 4.0, (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); barNum++; // startSamX += 2 * barWidth; startSamX += barWidth + barGap; } // display three info boxes below weighted means // each tic is the height of one calculated y-axis tic // determine the y axis tic double minYtic = Math.ceil(getMinY_Display() * 100) / 100; double maxYtic = Math.floor(getMaxY_Display() * 100) / 100; double deltay = Math.rint((maxYtic - minYtic) * 10 + 0.5); double yTic = deltay / 100; double yTopSummary = minPoint - yTic / 2.0;// wMeanOneSigma; //double specialYTic = yTic; double yTopWeights = yTopSummary - yTic * 1.1; double yTopMSWD_PDF = yTopWeights - yTic * 1.1; // summary box Path2D box = new Path2D.Double(Path2D.WIND_NON_ZERO); box.moveTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary - yTic, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary - yTic, getMaxY_Display(), rangeY, graphHeight)); box.closePath(); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(box); // Info Box g2d.drawString(// SAM.getAliquot().getAliquotName(), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 13f); g2d.drawString(// SAM.getName(), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 25f); g2d.drawString(// SAM.FormatValueAndTwoSigmaABSThreeWaysForPublication(6, 2), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 36f); g2d.drawString(// SAM.ShowCustomMSWDwithN(), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 48f); // weights box box.reset(); box.moveTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights - yTic, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights - yTic, getMaxY_Display(), rangeY, graphHeight)); box.closePath(); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(box); // plot fraction weights double artificialXRange = allFIDs.size(); double count = 0; //double weightWidth = Math.min(3.0 * barWidth, (yTic / rangeY * graphHeight)) - 15;//yTic;//barWidth * 2.0; double weightWidth = (barWidth + barGap) * 0.9; for (String fID : allFIDs) { // the dateModel has an associated aliquot, but in sample mode, it is a // standin aliquot for the sample. to get the aliquot number for // use in coloring fractions, we need to query the fraction itself String aliquotName = sample.getAliquotNameByFractionID(fID); Fraction f = ((UPbReduxAliquot) selectedSampleDateModels[i][0]) .getAliquotFractionByName(fID); Color includedFillColor = new Color(0, 0, 0); if (sample.getSampleDateInterpretationGUISettings().getAliquotOptions().get(aliquotName) .containsKey("includedFillColor")) { String[] temp = // sample.getSampleDateInterpretationGUISettings().getAliquotOptions() .get(aliquotName).get("includedFillColor").split(","); includedFillColor = buildRGBColor(temp); } double invertOneSigma = // 1.0 // / ((UPbReduxAliquot) selectedSampleDateModels[i][0]) .getAliquotFractionByName(fID)// .getRadiogenicIsotopeDateByName(SAM.getDateName()).getOneSigmaAbs() .movePointLeft(6).doubleValue(); Path2D weight = new Path2D.Double(Path2D.WIND_NON_ZERO); weight.moveTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.lineTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.lineTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.lineTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.closePath(); g2d.setStroke(new BasicStroke(2.5f)); // test for included or not == black or gray String weightPerCent = " 0";//0.0%"; // g2d.setPaint(includedFillColor); Composite originalComposite = g2d.getComposite(); if (SAM.getIncludedFractionIDsVector().contains(fID)) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f)); weightPerCent = formatter1DecPlace .format(Math.pow(invertOneSigma, 2.0) / totalWeight * 100.0);// + "%"; // april 2014 experiment if (f.getRgbColor() != 0) { includedFillColor = new Color(f.getRgbColor()); } } else { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); } g2d.setPaint(includedFillColor); g2d.fill(weight); //restore composite g2d.setComposite(originalComposite); // write percent of total weight g2d.drawString(weightPerCent, (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - yTic, getMaxY_Display(), rangeY, graphHeight) - 5f); g2d.setColor(Color.black); count += 1.0; } // double box height for graph yTic *= 2.0; // plot MSWD_PDF // store function x,y values Vector<Double> xVals = new Vector<Double>(); Vector<Double> yVals = new Vector<Double>(); double f = SAM.getIncludedFractionIDsVector().size() - 1; if (f > 1.0) { g2d.setStroke(new BasicStroke(1.0f)); double yRange = MSWDCoordinates.valuesByPointCount[(int) f][5] * 1.03; // alitle air at the top of curve double xStart = MSWDCoordinates.valuesByPointCount[(int) f][1]; double xRange = MSWDCoordinates.valuesByPointCount[(int) f][4] - xStart; double xStep = 0.005; Path2D MSWD_PDF = new Path2D.Double(Path2D.WIND_NON_ZERO); Path2D MSWD_right = new Path2D.Double(Path2D.WIND_NON_ZERO); // start at lower left corner of box (may or may not be 0,0 ) MSWD_PDF.moveTo(// (float) mapX((double) saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); // setup MSWD to paint last Path2D MSWD = null; // calculate function values for (double x = xStart; x < xRange; x += xStep) { xVals.add((((x - xStart) / xRange) * actualWidthX) + (double) saveStartSamX); double y = // Math.pow(2, -1.0 * f / 2.0)// * Math.exp(-1.0 * f * x / 2.0)// * Math.pow(f, f / 2.0)// * Math.pow(x, (-1.0 + f / 2.0))// / Math.exp(Gamma.logGamma(f / 2.0)); yVals.add(((y / yRange) * yTic) + yTopMSWD_PDF - yTic); MSWD_PDF.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); // test for location of left RED zone if ((MSWDCoordinates.valuesByPointCount[(int) f][2] >= x) && (MSWDCoordinates.valuesByPointCount[(int) f][2] < (x + xStep))) { double leftX = MSWDCoordinates.valuesByPointCount[(int) f][2]; xVals.add((((leftX - xStart) / xRange) * actualWidthX) + (double) saveStartSamX); double leftY = // Math.pow(2, -1.0 * f / 2.0)// * Math.exp(-1.0 * f * leftX / 2.0)// * Math.pow(f, f / 2.0)// * Math.pow(leftX, (-1.0 + f / 2.0))// / Math.exp(Gamma.logGamma(f / 2.0)); yVals.add(((leftY / yRange) * yTic) + yTopMSWD_PDF - yTic); MSWD_PDF.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); Path2D ciLower = new Path2D.Double(Path2D.WIND_NON_ZERO); ciLower.append(MSWD_PDF.getPathIterator(new AffineTransform()), true); ciLower.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); ciLower.closePath(); g2d.setColor(Color.RED); g2d.fill(ciLower); // draw right hand border line to compensate for a bug in the filler Line2D right = new Line2D.Double(// mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight), mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); g2d.setStroke(new BasicStroke(0.5f)); g2d.draw(right); g2d.setStroke(new BasicStroke(1.0f)); g2d.setColor(Color.BLACK); System.out.println("Left Red = (" + leftX + ", " + leftY + ")"); } // test for location of right RED zone if ((MSWDCoordinates.valuesByPointCount[(int) f][3] >= x) && (MSWDCoordinates.valuesByPointCount[(int) f][3] < (x + xStep))) { double rightX = MSWDCoordinates.valuesByPointCount[(int) f][3]; xVals.add((((rightX - xStart) / xRange) * actualWidthX) + (double) saveStartSamX); double rightY = // Math.pow(2, -1.0 * f / 2.0)// * Math.exp(-1.0 * f * rightX / 2.0)// * Math.pow(f, f / 2.0)// * Math.pow(rightX, (-1.0 + f / 2.0))// / Math.exp(Gamma.logGamma(f / 2.0)); yVals.add(((rightY / yRange) * yTic) + yTopMSWD_PDF - yTic); MSWD_PDF.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); // here the strategy is to draw the curve and then reset it to record the remainder g2d.setStroke(new BasicStroke(1.0f)); g2d.draw(MSWD_PDF); MSWD_PDF = new Path2D.Double(Path2D.WIND_NON_ZERO); MSWD_PDF.moveTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); MSWD_right.moveTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); MSWD_right.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); System.out.println("Right Red = (" + rightX + ", " + rightY + ")"); } // test for location of MSWD AND paint last if ((SAM.getMeanSquaredWeightedDeviation().doubleValue() >= x) && (SAM.getMeanSquaredWeightedDeviation().doubleValue() < (x + xStep))) { MSWD = new Path2D.Double(Path2D.WIND_NON_ZERO); MSWD.moveTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); MSWD.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); } } g2d.setStroke(new BasicStroke(1.0f)); // merge with border of right RED and fill MSWD_right.append(MSWD_PDF.getPathIterator(new AffineTransform()), true); g2d.setColor(Color.RED); g2d.fill(MSWD_right); g2d.setColor(Color.BLACK); // draw the remaining curves g2d.draw(MSWD_PDF); // MSWD may be off the graph and hence not exist try { g2d.draw(MSWD); } catch (Exception e) { } // label 95% conf interval and MSWD g2d.drawString(// "95% CI: (" + formatter2DecPlaces.format(MSWDCoordinates.valuesByPointCount[(int) f][2]) + ", " + formatter2DecPlaces.format(MSWDCoordinates.valuesByPointCount[(int) f][3]) + ")", (float) mapX(saveStartSamX + (actualWidthX / 2.0), getMinX_Display(), rangeX, graphWidth) - 30f, (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight) + 15f); // determine if MSWD is out of range String mswdAlert = ""; if (SAM.getMeanSquaredWeightedDeviation() .doubleValue() > MSWDCoordinates.valuesByPointCount[(int) f][4]) { mswdAlert = "\n !Out of Range!"; } g2d.drawString(// "MSWD = " + formatter2DecPlaces .format(SAM.getMeanSquaredWeightedDeviation().doubleValue()) + ", n = " + (int) (f + 1) + mswdAlert, (float) mapX(saveStartSamX + (actualWidthX / 2.0), getMinX_Display(), rangeX, graphWidth) - 15f, (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight) + 30f); } else { g2d.drawString("need more data...", (float) mapX((double) saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight) - 10f); } // MSWD_PDF box box.reset(); box.moveTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); box.closePath(); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(box); // MSWD_PDF x-axis tics if (f > 1.0) { g2d.setStroke(new BasicStroke(1.0f)); double xStart = (MSWDCoordinates.valuesByPointCount[(int) f][1] <= 0.5) ? 0.5 : 1.0; double xRange = MSWDCoordinates.valuesByPointCount[(int) f][4] - MSWDCoordinates.valuesByPointCount[(int) f][1]; double xStep = 0.5; for (double x = xStart; x < xRange; x += xStep) { double xPlot = (((x - MSWDCoordinates.valuesByPointCount[(int) f][1]) / xRange) * actualWidthX) + (double) saveStartSamX; Line2D line = new Line2D.Double(mapX(xPlot, getMinX_Display(), rangeX, graphWidth), mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight), mapX(xPlot, getMinX_Display(), rangeX, graphWidth), mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight) + 7); g2d.draw(line); g2d.rotate(-Math.PI / 2.0, (float) mapX(xPlot, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); g2d.drawString(formatter1DecPlace.format(x), (float) mapX(xPlot, getMinX_Display(), rangeX, graphWidth) - 30f, (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight) + 5f); g2d.rotate(Math.PI / 2.0, (float) mapX(xPlot, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); } } // set counters barNum += samSpace; startSamX += 2 * samSpace * barWidth; } } } // // prevents re-randomization // setInRandomMode( true ); drawAxesAndTicks(g2d, rangeX, rangeY); // draw zoom box if in use if ((Math.abs(zoomMaxX - zoomMinX) * Math.abs(zoomMinY - zoomMaxY)) > 0.0) { g2d.setStroke(new BasicStroke(2.0f)); g2d.setColor(Color.red); g2d.drawRect(// Math.min(zoomMinX, zoomMaxX), Math.min(zoomMaxY, zoomMinY), Math.abs(zoomMaxX - zoomMinX), Math.abs(zoomMinY - zoomMaxY)); } }
From source file:diet.gridr.g5k.util.ExtendedStackedBarRenderer.java
/** * Draws a stacked bar for a specific item. * * @param g2 the graphics device./*from w ww. j a va 2 s . co m*/ * @param state the renderer state. * @param dataArea the plot area. * @param plot the plot. * @param domainAxis the domain (category) axis. * @param rangeAxis the range (value) axis. * @param dataset the data. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // nothing is drawn for null values... Number dataValue = dataset.getValue(row, column); if (dataValue == null) { return; } double value = dataValue.doubleValue(); PlotOrientation orientation = plot.getOrientation(); double barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0; double positiveBase = 0.0; double negativeBase = 0.0; for (int i = 0; i < row; i++) { Number v = dataset.getValue(i, column); if (v != null) { double d = v.doubleValue(); if (d > 0) { positiveBase = positiveBase + d; } else { negativeBase = negativeBase + d; } } } double translatedBase; double translatedValue; RectangleEdge location = plot.getRangeAxisEdge(); if (value > 0.0) { translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea, location); translatedValue = rangeAxis.valueToJava2D(positiveBase + value, dataArea, location); } else { translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea, location); translatedValue = rangeAxis.valueToJava2D(negativeBase + value, dataArea, location); } double barL0 = Math.min(translatedBase, translatedValue); double barLength = Math.max(Math.abs(translatedValue - translatedBase), getMinimumBarLength()); Rectangle2D bar = null; if (orientation == PlotOrientation.HORIZONTAL) { bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth()); } else { bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength); } Paint seriesPaint = getItemPaint(row, column); g2.setPaint(seriesPaint); g2.fill(bar); if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) { g2.setStroke(getItemStroke(row, column)); g2.setPaint(getItemOutlinePaint(row, column)); g2.draw(bar); } CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column); if (generator != null && isItemLabelVisible(row, column)) { drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0)); } if (value > 0.0) { if (this.showPositiveTotal) { if (isLastPositiveItem(dataset, row, column)) { g2.setPaint(Color.black); g2.setFont(this.totalLabelFont); double total = calculateSumOfPositiveValuesForCategory(dataset, column); TextUtilities.drawRotatedString(this.totalFormatter.format(total), g2, (float) bar.getCenterX(), (float) (bar.getMinY() - 4.0), TextAnchor.BOTTOM_CENTER, 0.0, TextAnchor.BOTTOM_CENTER); } } } else { if (this.showNegativeTotal) { if (isLastNegativeItem(dataset, row, column)) { g2.setPaint(Color.black); g2.setFont(this.totalLabelFont); double total = calculateSumOfNegativeValuesForCategory(dataset, column); TextUtilities.drawRotatedString(String.valueOf(total), g2, (float) bar.getCenterX(), (float) (bar.getMaxY() + 4.0), TextAnchor.TOP_CENTER, 0.0, TextAnchor.TOP_CENTER); } } } // collect entity and tool tip information... if (state.getInfo() != null) { EntityCollection entities = state.getEntityCollection(); if (entities != null) { String tip = null; CategoryToolTipGenerator tipster = getToolTipGenerator(row, column); if (tipster != null) { tip = tipster.generateToolTip(dataset, row, column); } String url = null; if (getItemURLGenerator(row, column) != null) { url = getItemURLGenerator(row, column).generateURL(dataset, row, column); } CategoryItemEntity entity = new CategoryItemEntity(bar, tip, url, dataset, row, dataset.getColumnKey(column), column); entities.add(entity); } } }