List of usage examples for java.awt Graphics2D drawRect
public void drawRect(int x, int y, int width, int height)
From source file:figs.treeVisualization.gui.TimeAxisTree2DPanel.java
/** * Paint this Component using the Tree2DPainter with TimeBars * * @param g the graphics device// ww w . j av a 2 s . com */ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); /** * Enable antialiased graphics. */ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Dimension currentSize = this.getSize(); /** * Check to see if this component has changed size or if this * is our first time drawing. */ if (this.fDimension == null || !this.fDimension.equals(currentSize) || this.fTreeArea == null || this.fLeftTreeArea == null || this.fEstMaxDateWidth == null) { this.fDimension = currentSize; this.fTreeArea = new Rectangle2D.Double(0, 0, currentSize.getWidth(), currentSize.getHeight()); /** Adjust the width ratio using the maximum date width. */ this.refreshLeafNodes(); this.estimateMaximumDateWidth(g2); if ((this.fEstMaxDateWidth * 2) > (this.fTreeArea.getWidth() * this.fTreeWidthRatio) - this.fTreeArea.getWidth()) { this.fTreeWidthRatio = (this.fTreeArea.getWidth() - (this.fEstMaxDateWidth * 2)) / this.fTreeArea.getWidth(); } /** Make left tree area for tree. */ this.fLeftTreeArea = new Rectangle2D.Double(0, 0, this.fTreeArea.getWidth() * this.fTreeWidthRatio, this.fTreeArea.getHeight()); /** Now, clear the right tree area so that it will be recalculated. */ this.fRightTreeArea = null; } /** Paint the tree. */ this.fTreePainter.drawTree(g2, this.fLeftTreeArea); /** * Check to see if we have calculated the date data. * The order of this is very important. We need to have * called the painter before we can get the coordinates. */ if (this.fLeafNodes.isEmpty() || this.fLeafDates.isEmpty()) /** Just calculate the Leaf data. */ this.refreshLeafNodes(); /** * Draw the date axis and lines to the leaf nodes. */ if (fTopLeafDate != null || fBottomLeafDate != null) { if (this.fRightTreeArea == null) { calculateDateMargins(); this.fRightTreeArea = new Rectangle2D.Double(this.fTreeArea.getWidth() * this.fTreeWidthRatio, this.fTopLeafPt.getY(), this.fTreeArea.getWidth(), this.fBottomLeafPt.getY()); } double cursor = this.fRightTreeArea.getX() + ((this.fRightTreeArea.getWidth() - this.fRightTreeArea.getX()) / 2); drawDateAxis(g2, cursor, this.fRightTreeArea); drawDatesToLeafs(g2, cursor, this.fRightTreeArea); } else { // g2."No TIME INFORMATION AVAILABLE // g2.drawString("NO TIME INFORMATION AVAILABLE", x, y); System.out.println("TimeBarPanel: No time information available!"); } if (this.fMousePressed && this.fMouseSelectionRect != null) { /** Color of line varies depending on image colors. */ g2.setXORMode(Color.white); g2.drawRect(this.fMouseSelectionRect.x, this.fMouseSelectionRect.y, this.fMouseSelectionRect.width - 1, this.fMouseSelectionRect.height - 1); } }
From source file:org.executequery.gui.erd.ErdTable.java
protected void drawTable(Graphics2D g, int offsetX, int offsetY) { if (parent == null) { return;/*from ww w.j a v a2 s . co m*/ } Font tableNameFont = parent.getTableNameFont(); Font columnNameFont = parent.getColumnNameFont(); // set the table value background g.setColor(TITLE_BAR_BG_COLOR); g.fillRect(offsetX, offsetY, FINAL_WIDTH - 1, TITLE_BAR_HEIGHT); // set the table value FontMetrics fm = g.getFontMetrics(tableNameFont); int lineHeight = fm.getHeight(); int titleXPosn = (FINAL_WIDTH / 2) - (fm.stringWidth(tableName) / 2) + offsetX; g.setColor(Color.BLACK); g.setFont(tableNameFont); g.drawString(tableName, titleXPosn, lineHeight + offsetY); // draw the line separator lineHeight = TITLE_BAR_HEIGHT + offsetY - 1; g.drawLine(offsetX, lineHeight, offsetX + FINAL_WIDTH - 1, lineHeight); // fill the white background g.setColor(tableBackground); g.fillRect(offsetX, TITLE_BAR_HEIGHT + offsetY, FINAL_WIDTH - 1, FINAL_HEIGHT - TITLE_BAR_HEIGHT - 1); // add the column names fm = g.getFontMetrics(columnNameFont); int heightPlusSep = 1 + TITLE_BAR_HEIGHT + offsetY; int leftMargin = 5 + offsetX; lineHeight = fm.getHeight(); g.setColor(Color.BLACK); g.setFont(columnNameFont); int drawCount = 0; String value = null; if (ArrayUtils.isNotEmpty(columns)) { for (int i = 0; i < columns.length; i++) { ColumnData column = columns[i]; if (displayReferencedKeysOnly && !column.isKey()) { continue; } int y = (((drawCount++) + 1) * lineHeight) + heightPlusSep; int x = leftMargin; // draw the column value string value = column.getColumnName(); g.drawString(value, x, y); // draw the data type and size string x = leftMargin + dataTypeOffset; value = column.getFormattedDataType(); g.drawString(value, x, y); // draw the key label if (column.isKey()) { if (column.isPrimaryKey() && column.isForeignKey()) { value = PRIMARY + FOREIGN; } else if (column.isPrimaryKey()) { value = PRIMARY; } else if (column.isForeignKey()) { value = FOREIGN; } x = leftMargin + dataTypeOffset + keyLabelOffset; g.drawString(value, x, y); } } } // draw the rectangle border double scale = g.getTransform().getScaleX(); if (selected && scale != ErdPrintable.PRINT_SCALE) { g.setStroke(focusBorderStroke); g.setColor(Color.BLUE); } else { g.setColor(Color.BLACK); } g.drawRect(offsetX, offsetY, FINAL_WIDTH - 1, FINAL_HEIGHT - 1); // g.setColor(Color.DARK_GRAY); // g.draw3DRect(offsetX, offsetY, FINAL_WIDTH - 2, FINAL_HEIGHT - 2, true); }
From source file:org.cruk.mga.CreateReport.java
/** * Draws bars representing the total number of sequences for each dataset * and the assigned subsets for each species/reference genome to which * these have been aligned.//from w w w . ja v a 2s. c om * * @param g2 * @param offset * @param height * @param separation * @param x0 * @param x1 * @param maxSequenceCount * @param multiGenomeAlignmentSummaries */ private void drawAlignmentBars(Graphics2D g2, int offset, int height, int separation, int x0, int x1, long maxSequenceCount, Collection<MultiGenomeAlignmentSummary> multiGenomeAlignmentSummaries) { AlignmentSummaryComparator alignmentSummaryComparator = new AlignmentSummaryComparator(); g2.setColor(Color.BLACK); int y = offset; for (MultiGenomeAlignmentSummary multiGenomeAlignmentSummary : multiGenomeAlignmentSummaries) { int sampledCount = multiGenomeAlignmentSummary.getSampledCount(); long sequenceCount = multiGenomeAlignmentSummary.getSequenceCount(); log.debug(multiGenomeAlignmentSummary.getDatasetId() + " " + sequenceCount); Set<String> species = new HashSet<String>(); Set<String> controls = new HashSet<String>(); for (OrderedProperties sampleProperties : multiGenomeAlignmentSummary.getSampleProperties()) { String value = sampleProperties.getProperty(SPECIES_PROPERTY_NAMES); if (value != null) species.add(value); String control = sampleProperties.getProperty(CONTROL_PROPERTY_NAMES); if ("Yes".equals(control)) controls.add(value); } double width = (double) sequenceCount * (x1 - x0) / maxSequenceCount; int total = 0; int x = x0; // iterate over alignments for various reference genomes drawing bar for each List<AlignmentSummary> alignmentSummaryList = Arrays .asList(multiGenomeAlignmentSummary.getAlignmentSummaries()); Collections.sort(alignmentSummaryList, alignmentSummaryComparator); for (AlignmentSummary alignmentSummary : alignmentSummaryList) { total += alignmentSummary.getAssignedCount(); int w = (int) (width * total / sampledCount) - x + x0; String referenceGenomeId = alignmentSummary.getReferenceGenomeId(); String referenceGenomeName = getReferenceGenomeName(referenceGenomeId); Color color = Color.RED; if (controls.contains(referenceGenomeName)) { color = Color.ORANGE; } else if (species.contains(referenceGenomeName)) { color = Color.GREEN; } else if (species.isEmpty() || species.contains("Other") || species.contains("other")) { color = Color.GRAY; } float alpha = MAX_ALPHA - (MAX_ALPHA - MIN_ALPHA) * (alignmentSummary.getAssignedErrorRate() - MIN_ERROR) / (MAX_ERROR - MIN_ERROR); alpha = Math.max(alpha, MIN_ALPHA); alpha = Math.min(alpha, MAX_ALPHA); if (alignmentSummary.getAssignedCount() >= 100) log.debug(alignmentSummary.getReferenceGenomeId() + "\t" + alignmentSummary.getAssignedCount() + "\t" + alignmentSummary.getErrorRate() * 100.0f + "\t" + alpha); Composite origComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); g2.setColor(color); g2.fillRect(x, y, w, height); g2.setComposite(origComposite); g2.setColor(Color.BLACK); g2.drawRect(x, y, w, height); x += w; } // bar for all sequences g2.drawRect(x0, y, (int) width, height); // bar for adapter sequences int adapterCount = multiGenomeAlignmentSummary.getAdapterCount(); log.debug("Adapter count: " + adapterCount + " / " + sampledCount); int ya = y + height + height / 5; double wa = width * adapterCount / sampledCount; if (wa > 2) { int ha = height / 3; g2.setColor(ADAPTER_COLOR); g2.fillRect(x0, ya, (int) wa, ha); g2.setColor(Color.BLACK); g2.drawRect(x0, ya, (int) wa, ha); } y += separation; } }
From source file:org.tsho.dmc2.core.chart.Bifurcation2DRenderer.java
public void render(final Graphics2D g2, final Rectangle2D dataArea, final PlotRenderingInfo info) { int numVar = model.getNVar(); if (model instanceof ODE) { boolean pointBeyondPoincareSection; ValueAxis domainAxis = plot.getDomainAxis(); ValueAxis rangeAxis = plot.getRangeAxis(); int dim = initialValue.length; final int colorArrayLen = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length; final Paint[] colorArray = new Color[colorArrayLen]; for (int i = 0; i < colorArrayLen; i++) { colorArray[i] = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i]; }//www . ja v a 2s . com double[] fPars = new double[fixedParameters.length]; System.arraycopy(fixedParameters, 0, fPars, 0, fixedParameters.length); double[] initVars = new double[initialValue.length]; System.arraycopy(initialValue, 0, initVars, 0, initialValue.length); double[] result = new double[dim]; double[][] periodArray = new double[period][dim]; for (double i = dataArea.getMinX(); i <= dataArea.getMaxX(); i += 1) { fPars[firstParameterIdx] = domainAxis.java2DToValue(i, dataArea, RectangleEdge.BOTTOM); for (double j = dataArea.getMinY(); j < dataArea.getMaxY(); j += 1) { fPars[secondParameterIdx] = rangeAxis.java2DToValue(j, dataArea, RectangleEdge.LEFT); stepper.setParameters(fPars); stepper.setInitialValue(initVars); stepper.initialize(); stepper.step(); stepper.getCurrentValue(result); int h = 0; int transX, transY; double[] currentPoint = new double[numVar]; double[] previousPoint = new double[numVar]; stepper.getCurrentValue(currentPoint); stepper.getCurrentValue(previousPoint); pointBeyondPoincareSection = positionWrtPoincareSection(currentPoint); Paint color = Color.white; double[] cycleStartPoint = new double[numVar]; int actualPeriod = period + 1; for (int jj = 0; jj < time / step; jj++) { stepper.step(); stepper.getCurrentValue(currentPoint); if (positionWrtPoincareSection(currentPoint) == pointBeyondPoincareSection) { stepper.getCurrentValue(previousPoint); continue; } pointBeyondPoincareSection = !pointBeyondPoincareSection; double[] pointOnSection = pointOnPoincareSection(previousPoint, currentPoint); stepper.setInitialValue(pointOnSection); stepper.initialize(); stepper.getCurrentValue(currentPoint); stepper.getCurrentValue(previousPoint); h++; if (h == transients) { for (int kk = 0; kk < numVar; kk++) cycleStartPoint[kk] = currentPoint[kk]; } if (h > transients) { if (distance(currentPoint, cycleStartPoint) < epsilon) { actualPeriod = h - transients; break; } if (h >= transients + period) break; } } stepper.getCurrentValue(result); for (h = 0; h < dim; h++) { if (Math.abs(result[h]) > infinity || Double.isNaN(result[h])) { color = Color.black; // black == infinity } } if (stopped) { state = STATE_STOPPED; return; } if (actualPeriod <= period) { // found period color = colorArray[actualPeriod - 1]; } g2.setPaint(color); g2.drawRect((int) i, (int) j, 1, 1); if (stopped) { state = STATE_STOPPED; return; } } } state = STATE_FINISHED; } else { ValueAxis domainAxis = plot.getDomainAxis(); ValueAxis rangeAxis = plot.getRangeAxis(); int dim = initialValue.length; final int colorArrayLen = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length; final Paint[] colorArray = new Color[colorArrayLen]; for (int i = 0; i < colorArrayLen; i++) { colorArray[i] = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i]; } double[] fPars = new double[fixedParameters.length]; System.arraycopy(fixedParameters, 0, fPars, 0, fixedParameters.length); double[] initVars = new double[initialValue.length]; System.arraycopy(initialValue, 0, initVars, 0, initialValue.length); double[] result = new double[dim]; double[][] periodArray = new double[period + 1][dim]; for (double i = dataArea.getMinX(); i <= dataArea.getMaxX(); i += 1) { fPars[firstParameterIdx] = domainAxis.java2DToValue(i, dataArea, RectangleEdge.BOTTOM); for (double j = dataArea.getMinY(); j < dataArea.getMaxY(); j += 1) { fPars[secondParameterIdx] = rangeAxis.java2DToValue(j, dataArea, RectangleEdge.LEFT); stepper.setParameters(fPars); stepper.setInitialValue(initVars); stepper.initialize(); stepper.step(); stepper.getCurrentValue(result); for (int h = 1; h < transients; h++) { if (stopped) { state = STATE_STOPPED; return; } stepper.step(); } stepper.getCurrentValue(result); Paint color = Color.white; // white == longer period for (int h = 0; h < dim; h++) { if (Math.abs(result[h]) > infinity || Double.isNaN(result[h])) { color = Color.black; // black == infinity break; } } if (color != Color.black) { // get maxPeriod next values for (int h = 0; h <= period; h++) { if (stopped) { state = STATE_STOPPED; return; } stepper.step(); stepper.getCurrentValue(result); for (int k = 0; k < dim; k++) { periodArray[h][k] = result[k]; } } int h, k = -1; for (h = 1; h <= period; h++) { for (k = 0; k < dim; k++) { if (Math.abs(periodArray[0][k] - periodArray[h][k]) >= epsilon) { break; } } if (k == dim) { break; } } if (h <= period) { // found period color = colorArray[h - 1]; } } g2.setPaint(color); g2.drawRect((int) i, (int) j, 1, 1); if (stopped) { state = STATE_STOPPED; return; } } } state = STATE_FINISHED; } }
From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java
/** * Actually draws the environment on the view. * /*from w w w. ja v a 2 s .c o m*/ * @param g * {@link Graphics2D} object responsible for drawing */ protected final void drawEnvOnView(final Graphics2D g) { if (wormhole == null || !isVisible() || !isEnabled()) { return; } accessData(); if (hooked.isPresent()) { final Position hcoor = positions.get(hooked.get()); final Point hp = wormhole.getViewPoint(hcoor); if (hp.distance(getCenter()) > FREEDOM_RADIUS) { wormhole.setViewPosition(hp); } } /* * Compute nodes in sight and their screen position */ final Map<Node<T>, Point> onView = positions.entrySet().parallelStream() .map(pair -> new Pair<>(pair.getKey(), wormhole.getViewPoint(pair.getValue()))) .filter(p -> wormhole.isInsideView(p.getSecond())) .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); g.setColor(Color.BLACK); if (obstacles != null) { /* * TODO: only draw obstacles if on view */ obstacles.parallelStream().map(this::convertObstacle).forEachOrdered(g::fill); } if (paintLinks) { g.setColor(Color.GRAY); onView.keySet().parallelStream().map(neighbors::get) .flatMap(neigh -> neigh.getNeighbors().parallelStream() .map(node -> node.compareTo(neigh.getCenter()) > 0 ? new Pair<>(neigh.getCenter(), node) : new Pair<>(node, neigh.getCenter()))) .distinct().map( pair -> mapPair(pair, node -> Optional.ofNullable(onView.get(node)) .orElse(wormhole.getViewPoint(positions.get(node))))) .forEachOrdered(line -> { final Point p1 = line.getFirst(); final Point p2 = line.getSecond(); g.drawLine(p1.x, p1.y, p2.x, p2.y); }); } releaseData(); if (isDraggingMouse && status == ViewStatus.MOVING && originPoint.isPresent() && endingPoint.isPresent()) { for (final Node<T> n : selectedNodes) { if (onView.containsKey(n)) { onView.put(n, new Point(onView.get(n).x + (endingPoint.get().x - originPoint.get().x), onView.get(n).y + (endingPoint.get().y - originPoint.get().y))); } } } g.setColor(Color.GREEN); if (effectStack != null) { effectStack.forEach(effect -> { onView.entrySet().forEach(entry -> { final Point p = entry.getValue(); effect.apply(g, entry.getKey(), p.x, p.y); }); }); } if (isCloserNodeMarked()) { final Optional<Map.Entry<Node<T>, Point>> closest = onView.entrySet().parallelStream() .min((pair1, pair2) -> { final Point p1 = pair1.getValue(); final Point p2 = pair2.getValue(); final double d1 = Math.hypot(p1.x - mousex, p1.y - mousey); final double d2 = Math.hypot(p2.x - mousex, p2.y - mousey); return Double.compare(d1, d2); }); if (closest.isPresent()) { nearest = closest.get().getKey(); final int nearestx = closest.get().getValue().x; final int nearesty = closest.get().getValue().y; drawFriedEgg(g, nearestx, nearesty, Color.RED, Color.YELLOW); } } else { nearest = null; } if (isDraggingMouse && status == ViewStatus.SELECTING && originPoint.isPresent() && endingPoint.isPresent()) { g.setColor(Color.BLACK); final int x = originPoint.get().x < endingPoint.get().x ? originPoint.get().x : endingPoint.get().x; final int y = originPoint.get().y < endingPoint.get().y ? originPoint.get().y : endingPoint.get().y; final int width = Math.abs(endingPoint.get().x - originPoint.get().x); final int height = Math.abs(endingPoint.get().y - originPoint.get().y); g.drawRect(x, y, width, height); selectedNodes = onView.entrySet().parallelStream() .filter(nodes -> isInsideRectangle(nodes.getValue(), x, y, width, height)) .map(onScreen -> onScreen.getKey()).collect(Collectors.toSet()); } selectedNodes.parallelStream().map(e -> Optional.ofNullable(onView.get(e))).filter(Optional::isPresent) .map(Optional::get).forEachOrdered(p -> drawFriedEgg(g, p.x, p.y, Color.BLUE, Color.CYAN)); }
From source file:org.gumtree.vis.awt.JChartPanel.java
private void drawTextInputBox(Graphics2D g2) { if (textInputFlag && textInputPoint != null) { // g2.drawChars("Input Text Here".toCharArray(), 1, 60, (int) textInputPoint.getX(), (int) textInputPoint.getY()); Color oldColor = g2.getColor(); g2.setColor(Color.BLACK); String inputText = textInputContent == null ? "" : textInputContent; FontMetrics fm = g2.getFontMetrics(); // int sWidth; // if (textInputCursorIndex == 0 || inputText.length() == 0) { // sWidth = 0; // } else if (textInputCursorIndex < inputText.length()){ // sWidth = fm.stringWidth(inputText.substring(0, textInputCursorIndex)); // } else { // sWidth = fm.stringWidth(inputText); // } String[] lines = inputText.split("\n", 100); int cursorY = 0; int cursorX = 0; int charCount = 0; int maxWidth = 0; int maxHeight = 0; for (int i = 0; i < lines.length; i++) { g2.drawString(lines[i], (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3 + i * 15); // charCount += lines[i].length() + 1; if (textInputCursorIndex > charCount && textInputCursorIndex < charCount + lines[i].length() + 1) { cursorY = i;//from w ww.j ava2 s . c om cursorX = fm.stringWidth(lines[i].substring(0, textInputCursorIndex - charCount)); } else if (textInputCursorIndex == charCount + lines[i].length() + 1) { cursorY = i + 1; cursorX = 0; } charCount += lines[i].length() + 1; int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } maxHeight = 15 * lines.length; // g2.drawString(inputText, (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3); g2.setColor(Color.MAGENTA); // g2.drawString("|", (float) textInputPoint.getX() + 2 + sWidth, (float) textInputPoint.getY() - 3); g2.drawLine((int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + (cursorY - 1) * 15, (int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + cursorY * 15); g2.setColor(Color.BLACK); g2.setColor(oldColor); // int boxWidth = fm.stringWidth(inputText) + 10; if (maxWidth < 100) { maxWidth = 100; } Rectangle2D inputBox = new Rectangle2D.Double(textInputPoint.getX(), textInputPoint.getY() - 15, maxWidth + 8, maxHeight); // ChartMaskingUtilities.drawMaskBoarder(g2, inputBox); Color fillColor = new Color(250, 250, 50, 30); g2.setPaint(fillColor); g2.fill(inputBox); g2.setColor(Color.ORANGE); g2.drawRect((int) textInputPoint.getX(), (int) textInputPoint.getY() - 15, maxWidth + 8, maxHeight); } if (textContentMap.size() > 0) { Color oldColor = g2.getColor(); g2.setColor(Color.BLACK); Rectangle2D imageArea = getScreenDataArea(); for (Entry<Rectangle2D, String> entry : textContentMap.entrySet()) { Rectangle2D rect = entry.getKey(); Point2D screenPoint = ChartMaskingUtilities .translateChartPoint(new Point2D.Double(rect.getX(), rect.getY()), imageArea, getChart()); String text = entry.getValue(); if (text == null) { continue; } String[] lines = text.split("\n"); g2.setColor(Color.BLACK); for (int i = 0; i < lines.length; i++) { g2.drawString(lines[i], (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3 + i * 15); } if (rect == selectedTextWrapper) { FontMetrics fm = g2.getFontMetrics(); int maxWidth = 0; int maxHeight = 0; for (int i = 0; i < lines.length; i++) { int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } maxHeight = 15 * lines.length; if (maxWidth < 100) { maxWidth = 100; } Rectangle2D inputBox = new Rectangle2D.Double(screenPoint.getX(), screenPoint.getY() - 15, maxWidth + 8, maxHeight); Color fillColor = new Color(250, 250, 50, 30); g2.setPaint(fillColor); g2.fill(inputBox); g2.setColor(Color.ORANGE); g2.drawRect((int) screenPoint.getX(), (int) screenPoint.getY() - 15, maxWidth + 8, maxHeight); } // g2.drawString(text == null ? "" : text, (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3); } g2.setColor(oldColor); } }
From source file:org.photovault.swingui.PhotoCollectionThumbView.java
private void paintThumbnail(Graphics2D g2, PhotoInfo photo, int startx, int starty, boolean isSelected) { log.debug("paintThumbnail entry " + photo.getUuid()); long startTime = System.currentTimeMillis(); long thumbReadyTime = 0; long thumbDrawnTime = 0; long endTime = 0; // Current position in which attributes can be drawn int ypos = starty + rowHeight / 2; boolean useOldThumbnail = false; Thumbnail thumbnail = null;/*from w ww .ja va 2 s. c o m*/ log.debug("finding thumb"); boolean hasThumbnail = photo.hasThumbnail(); log.debug("asked if has thumb"); if (hasThumbnail) { log.debug("Photo " + photo.getUuid() + " has thumbnail"); thumbnail = photo.getThumbnail(); log.debug("got thumbnail"); } else { /* Check if the thumbnail has been just invalidated. If so, use the old one until we get the new thumbnail created. */ thumbnail = photo.getOldThumbnail(); if (thumbnail != null) { useOldThumbnail = true; } else { // No success, use default thumnail. thumbnail = Thumbnail.getDefaultThumbnail(); } // Inform background task scheduler that we have some work to do ctrl.getBackgroundTaskScheduler().registerTaskProducer(this, TaskPriority.CREATE_VISIBLE_THUMBNAIL); } thumbReadyTime = System.currentTimeMillis(); log.debug("starting to draw"); // Find the position for the thumbnail BufferedImage img = thumbnail.getImage(); if (img == null) { thumbnail = Thumbnail.getDefaultThumbnail(); img = thumbnail.getImage(); } float scaleX = ((float) thumbWidth) / ((float) img.getWidth()); float scaleY = ((float) thumbHeight) / ((float) img.getHeight()); float scale = Math.min(scaleX, scaleY); int w = (int) (img.getWidth() * scale); int h = (int) (img.getHeight() * scale); int x = startx + (columnWidth - w) / (int) 2; int y = starty + (rowHeight - h) / (int) 2; log.debug("drawing thumbnail"); // Draw shadow int offset = isSelected ? 2 : 0; int shadowX[] = { x + 3 - offset, x + w + 1 + offset, x + w + 1 + offset }; int shadowY[] = { y + h + 1 + offset, y + h + 1 + offset, y + 3 - offset }; GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, shadowX.length); polyline.moveTo(shadowX[0], shadowY[0]); for (int index = 1; index < shadowX.length; index++) { polyline.lineTo(shadowX[index], shadowY[index]); } ; BasicStroke shadowStroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); Stroke oldStroke = g2.getStroke(); g2.setStroke(shadowStroke); g2.setColor(Color.DARK_GRAY); g2.draw(polyline); g2.setStroke(oldStroke); // Paint thumbnail g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(img, new AffineTransform(scale, 0f, 0f, scale, x, y), null); if (useOldThumbnail) { creatingThumbIcon.paintIcon(this, g2, startx + (columnWidth - creatingThumbIcon.getIconWidth()) / (int) 2, starty + (rowHeight - creatingThumbIcon.getIconHeight()) / (int) 2); } log.debug("Drawn, drawing decorations"); if (isSelected) { Stroke prevStroke = g2.getStroke(); Color prevColor = g2.getColor(); g2.setStroke(new BasicStroke(3.0f)); g2.setColor(Color.BLUE); g2.drawRect(x, y, w, h); g2.setColor(prevColor); g2.setStroke(prevStroke); } thumbDrawnTime = System.currentTimeMillis(); boolean drawAttrs = (thumbWidth >= 100); if (drawAttrs) { // Increase ypos so that attributes are drawn under the image ypos += ((int) h) / 2 + 3; // Draw the attributes // Draw the qualoity icon to the upper left corner of the thumbnail int quality = photo.getQuality(); if (showQuality && quality != 0) { int qx = startx + (columnWidth - quality * starIcon.getIconWidth()) / (int) 2; for (int n = 0; n < quality; n++) { starIcon.paintIcon(this, g2, qx, ypos); qx += starIcon.getIconWidth(); } ypos += starIcon.getIconHeight(); } ypos += 6; if (photo.getRawSettings() != null) { // Draw the "RAW" icon int rx = startx + (columnWidth + w - rawIcon.getIconWidth()) / (int) 2 - 5; int ry = starty + (columnWidth - h - rawIcon.getIconHeight()) / (int) 2 + 5; rawIcon.paintIcon(this, g2, rx, ry); } if (photo.getHistory().getHeads().size() > 1) { // Draw the "unresolved conflicts" icon int rx = startx + (columnWidth + w - 10) / (int) 2 - 20; int ry = starty + (columnWidth - h - 10) / (int) 2; g2.setColor(Color.RED); g2.fillRect(rx, ry, 10, 10); } Color prevBkg = g2.getBackground(); if (isSelected) { g2.setBackground(Color.BLUE); } else { g2.setBackground(this.getBackground()); } Font attrFont = new Font("Arial", Font.PLAIN, 10); FontRenderContext frc = g2.getFontRenderContext(); if (showDate && photo.getShootTime() != null) { FuzzyDate fd = new FuzzyDate(photo.getShootTime(), photo.getTimeAccuracy()); String dateStr = fd.format(); TextLayout txt = new TextLayout(dateStr, attrFont, frc); // Calculate the position for the text Rectangle2D bounds = txt.getBounds(); int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX(); g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4); txt.draw(g2, xpos, (int) (ypos + bounds.getHeight())); ypos += bounds.getHeight() + 4; } String shootPlace = photo.getShootingPlace(); if (showPlace && shootPlace != null && shootPlace.length() > 0) { TextLayout txt = new TextLayout(photo.getShootingPlace(), attrFont, frc); // Calculate the position for the text Rectangle2D bounds = txt.getBounds(); int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX(); g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4); txt.draw(g2, xpos, (int) (ypos + bounds.getHeight())); ypos += bounds.getHeight() + 4; } g2.setBackground(prevBkg); } endTime = System.currentTimeMillis(); log.debug("paintThumbnail: exit " + photo.getUuid()); log.debug("Thumb fetch " + (thumbReadyTime - startTime) + " ms"); log.debug("Thumb draw " + (thumbDrawnTime - thumbReadyTime) + " ms"); log.debug("Deacoration draw " + (endTime - thumbDrawnTime) + " ms"); log.debug("Total " + (endTime - startTime) + " ms"); }
From source file:au.org.ala.biocache.web.WMSController.java
void drawUncertaintyCircles(SpatialSearchRequestParams requestParams, WmsEnv vars, int height, int width, double[] pbbox, double[] mbbox, double width_mult, double height_mult, Graphics2D g, String[] originalFqs, String[] boundingBoxFqs, boolean is4326, double[] tilebbox) throws Exception { //draw uncertainty circles double hmult = (height / (mbbox[3] - mbbox[1])); //only draw uncertainty if max radius will be > 1 pixels if (vars.uncertainty && MAX_UNCERTAINTY * hmult > 1) { //uncertainty colour/fq/radius, [0]=map, [1]=not specified, [2]=too large Color[] uncertaintyColours = { new Color(255, 170, 0, vars.alpha), new Color(255, 255, 100, vars.alpha), new Color(50, 255, 50, vars.alpha) }; //TODO: don't assume MAX_UNCERTAINTY > default_uncertainty String[] uncertaintyFqs = { "coordinate_uncertainty:[* TO " + MAX_UNCERTAINTY + "] AND -assertions:uncertaintyNotSpecified", "assertions:uncertaintyNotSpecified", "coordinate_uncertainty:[" + MAX_UNCERTAINTY + " TO *]" }; double[] uncertaintyR = { -1, MAX_UNCERTAINTY, MAX_UNCERTAINTY }; String[] fqs = new String[originalFqs.length + 3]; System.arraycopy(originalFqs, 0, fqs, 3, originalFqs.length); fqs[1] = boundingBoxFqs[0];//from w ww . j a v a 2 s.c o m fqs[2] = boundingBoxFqs[1]; requestParams.setPageSize(DEFAULT_PAGE_SIZE); for (int j = 0; j < uncertaintyFqs.length; j++) { //do not display for [1]=not specified if (j == 1) { continue; } fqs[0] = uncertaintyFqs[j]; requestParams.setFq(fqs); requestParams.setFl("longitude,latitude,coordinate_uncertainty"); //only retrieve longitude and latitude requestParams.setFacet(false); //TODO: paging SolrDocumentList sdl = searchDAO.findByFulltext(requestParams); //for 4326 double top = tilebbox[3]; double bottom = tilebbox[1]; double left = tilebbox[0]; double right = tilebbox[2]; double lng, lat; int x, y; int uncertaintyRadius = (int) Math.ceil(uncertaintyR[j] * hmult); if (sdl != null && sdl.size() > 0) { g.setColor(uncertaintyColours[j]); for (int i = 0; i < sdl.size(); i++) { if (uncertaintyR[j] < 0) { uncertaintyRadius = (int) Math .ceil((Double) sdl.get(i).getFieldValue("coordinate_uncertainty") * hmult); } lng = (Double) sdl.get(i).getFieldValue("longitude"); lat = (Double) sdl.get(i).getFieldValue("latitude"); if (is4326) { x = convertLngToPixel4326(lng, left, right, width); y = convertLatToPixel4326(lat, top, bottom, height); } else { x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult); y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult); } if (uncertaintyRadius > 0) { g.drawOval(x - uncertaintyRadius, y - uncertaintyRadius, uncertaintyRadius * 2, uncertaintyRadius * 2); } else { g.drawRect(x, y, 1, 1); } } } } } }
From source file:org.pmedv.blackboard.components.BoardEditor.java
@Override protected void paintComponent(Graphics g) { Boolean useLayerColor = (Boolean) Preferences.values .get("org.pmedv.blackboard.BoardDesignerPerspective.useLayerColor"); // clear all // g.clearRect(0, 0, getWidth(), getHeight()); g.setColor(BLANK);/*from w w w . j ava2 s .c o m*/ g.fillRect(0, 0, getWidth(), getHeight()); // some nice anti aliasing... Graphics2D g2 = (Graphics2D) g; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHints(rh); // TODO : Should this be done here? // Sort layers by z-index g2.setColor(Color.LIGHT_GRAY); g2.setStroke(BoardUtil.stroke_1_0f); Collections.sort(model.getLayers()); for (int i = model.getLayers().size() - 1; i >= 0; i--) { // Sort items by z-index Collections.sort(model.getLayers().get(i).getItems()); drawLayer(model.getLayers().get(i), g2); } // draw selection border if (state.equals(SelectionState.DRAGGING_NEW_SELECTION) && button1Pressed) { g2.setColor(Color.GREEN); g2.setStroke(BoardUtil.stroke_1_0f); if (dragStopX < dragStartX && dragStopY > dragStartY) { selectionBorder.setSize(dragStartX - dragStopX, dragStopY - dragStartY); selectionBorder.setLocation(dragStopX, dragStartY); } else if (dragStopY < dragStartY && dragStopX > dragStartX) { selectionBorder.setSize(dragStopX - dragStartX, dragStartY - dragStopY); selectionBorder.setLocation(dragStartX, dragStopY); } else if (dragStopX < dragStartX && dragStopY < dragStartY) { selectionBorder.setSize(dragStartX - dragStopX, dragStartY - dragStopY); selectionBorder.setLocation(dragStopX, dragStopY); } else { selectionBorder.setSize(dragStopX - dragStartX, dragStopY - dragStartY); selectionBorder.setLocation(dragStartX, dragStartY); } g2.draw(selectionBorder); } // display shape currently being drawed if (lineStartX > 0 && lineStartY > 0 && lineStopX > 0 && lineStopY > 0) { if (useLayerColor) g2.setColor(model.getCurrentLayer().getColor()); else g2.setColor(palette.getCurrentColor()); g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem()); // draw new line if (editorMode.equals(EditorMode.DRAW_LINE)) { if (useLayerColor) currentDrawingLine.setColor(model.getCurrentLayer().getColor()); else currentDrawingLine.setColor(palette.getCurrentColor()); currentDrawingLine.setStartType((LineEdgeType) shapesPanel.getStartLineCombo().getSelectedItem()); currentDrawingLine.setEndType((LineEdgeType) shapesPanel.getEndLineCombo().getSelectedItem()); currentDrawingLine.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem()); currentDrawingLine.getStart().setLocation(lineStartX, lineStartY); currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY); currentDrawingLine.draw(g2); } else if (editorMode.equals(EditorMode.DRAW_MEASURE)) { currentDrawingLine.setStroke(Measure.DEFAULT_STROKE); currentDrawingLine.getStart().setLocation(lineStartX, lineStartY); currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY); currentDrawingLine.draw(g2); } // draw new box or ellipse else if (editorMode.equals(EditorMode.DRAW_RECTANGLE) || editorMode.equals(EditorMode.DRAW_ELLIPSE)) { int xLoc = lineStartX; int yLoc = lineStartY; int width = lineStopX - lineStartX; int height = lineStopY - lineStartY; ShapeStyle style = (ShapeStyle) shapesPanel.getStyleCombo().getSelectedItem(); if (style == null || style.equals(ShapeStyle.FILLED)) { if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) { g2.fillRect(xLoc, yLoc, width, height); } else { g2.fillOval(xLoc, yLoc, width, height); } } else if (style.equals(ShapeStyle.OUTLINED)) { g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem()); if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) { g2.drawRect(xLoc, yLoc, width, height); } else { g2.drawOval(xLoc, yLoc, width, height); } } } } // draw selection handles if (selectedItem != null) { g2.setStroke(BoardUtil.stroke_1_0f); g2.setColor(Color.GREEN); selectedItem.drawHandles(g2, 8); } // draw border if (zoomLayer != null) { TransformUI ui = (TransformUI) (Object) zoomLayer.getUI(); DefaultTransformModel xmodel = (DefaultTransformModel) ui.getModel(); if (xmodel.isMirror()) { g2.setColor(Color.RED); } else { g2.setColor(Color.GREEN); } } else { g2.setColor(Color.GREEN); } g2.setStroke(DEFAULT_STROKE); Rectangle border = new Rectangle(0, 0, model.getWidth() - 1, model.getHeight() - 1); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.draw(border); if (model.getType().equals(BoardType.STRIPES) || model.getType().equals(BoardType.HOLES)) { g2.setColor(Color.BLACK); g2.setFont(miniFont); int index = 1; for (int x = 12; x < model.getWidth() - 16; x += 16) { g2.drawString(String.valueOf(index++), x, 8); } index = 1; for (int y = 18; y < model.getHeight(); y += 16) { g2.drawString(String.valueOf(index++), 3, y); } } if (editorMode.equals(EditorMode.CHECK_CONNECTIONS)) { if (connectedLines != null) { for (Line line : connectedLines) { line.drawFat(g2); } } } if (drawing) { g2.setColor(Color.BLUE); g2.setStroke(DEFAULT_STROKE); if (selectedPin != null) { g2.drawRect(lineStopX - 8, lineStopY - 8, 16, 16); } } super.paintComponents(g2); }
From source file:de.tor.tribes.ui.panels.MinimapPanel.java
private boolean redraw() { Village[][] mVisibleVillages = DataHolder.getSingleton().getVillages(); if (mVisibleVillages == null || mBuffer == null) { return false; }//from w w w.j av a 2 s. c om Graphics2D g2d = (Graphics2D) mBuffer.getGraphics(); Composite tempC = g2d.getComposite(); //clear g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR)); g2d.fillRect(0, 0, mBuffer.getWidth(), mBuffer.getHeight()); //reset composite g2d.setComposite(tempC); boolean markPlayer = GlobalOptions.getProperties().getBoolean("mark.villages.on.minimap"); if (ServerSettings.getSingleton().getMapDimension() == null) { //could not draw minimap if dimensions are not loaded yet return false; } boolean showBarbarian = GlobalOptions.getProperties().getBoolean("show.barbarian"); Color DEFAULT = Constants.DS_DEFAULT_MARKER; try { int mark = Integer.parseInt(GlobalOptions.getProperty("default.mark")); if (mark == 0) { DEFAULT = Constants.DS_DEFAULT_MARKER; } else if (mark == 1) { DEFAULT = Color.RED; } else if (mark == 2) { DEFAULT = Color.WHITE; } } catch (Exception e) { DEFAULT = Constants.DS_DEFAULT_MARKER; } Rectangle mapDim = ServerSettings.getSingleton().getMapDimension(); double wField = mapDim.getWidth() / (double) visiblePart.width; double hField = mapDim.getHeight() / (double) visiblePart.height; UserProfile profile = GlobalOptions.getSelectedProfile(); Tribe currentTribe = InvalidTribe.getSingleton(); if (profile != null) { currentTribe = profile.getTribe(); } for (int i = visiblePart.x; i < (visiblePart.width + visiblePart.x); i++) { for (int j = visiblePart.y; j < (visiblePart.height + visiblePart.y); j++) { Village v = mVisibleVillages[i][j]; if (v != null) { Color markerColor = null; boolean isLeft = false; if (v.getTribe() == Barbarians.getSingleton()) { isLeft = true; } else { if ((currentTribe != null) && (v.getTribe().getId() == currentTribe.getId())) { //village is owned by current player. mark it dependent on settings if (markPlayer) { markerColor = Color.YELLOW; } } else { try { Marker marker = MarkerManager.getSingleton().getMarker(v.getTribe()); if (marker != null && !marker.isShownOnMap()) { marker = null; markerColor = DEFAULT; } if (marker == null) { marker = MarkerManager.getSingleton().getMarker(v.getTribe().getAlly()); if (marker != null && marker.isShownOnMap()) { markerColor = marker.getMarkerColor(); } } else { if (marker.isShownOnMap()) { markerColor = marker.getMarkerColor(); } } } catch (Exception e) { markerColor = null; } } } if (!isLeft) { if (markerColor != null) { g2d.setColor(markerColor); } else { g2d.setColor(DEFAULT); } g2d.fillRect((int) Math.round((i - visiblePart.x) * wField), (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField), (int) Math.floor(hField)); } else { if (showBarbarian) { g2d.setColor(Color.LIGHT_GRAY); g2d.fillRect((int) Math.round((i - visiblePart.x) * wField), (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField), (int) Math.floor(hField)); } } } } } try { if (GlobalOptions.getProperties().getBoolean("map.showcontinents")) { g2d.setColor(Color.BLACK); Composite c = g2d.getComposite(); Composite a = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f); Font f = g2d.getFont(); Font t = new Font("Serif", Font.BOLD, (int) Math.round(30 * hField)); g2d.setFont(t); int fact = 10; int mid = (int) Math.round(50 * wField); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { g2d.setComposite(a); String conti = "K" + (j * 10 + i); Rectangle2D bounds = g2d.getFontMetrics(t).getStringBounds(conti, g2d); int cx = i * fact * 10 - visiblePart.x; int cy = j * fact * 10 - visiblePart.y; cx = (int) Math.round(cx * wField); cy = (int) Math.round(cy * hField); g2d.drawString(conti, (int) Math.rint(cx + mid - bounds.getWidth() / 2), (int) Math.rint(cy + mid + bounds.getHeight() / 2)); g2d.setComposite(c); int wk = 100; int hk = 100; if (i == 9) { wk -= 1; } if (j == 9) { hk -= 1; } g2d.drawRect(cx, cy, (int) Math.round(wk * wField), (int) Math.round(hk * hField)); } } g2d.setFont(f); } } catch (Exception e) { logger.error("Creation of Minimap failed", e); } g2d.dispose(); return true; }