List of usage examples for java.awt Graphics2D getFont
public abstract Font getFont();
From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java
private void renderDayMarkers(long pStart, long pEnd, Graphics2D pG2D) { Date d = new Date(pStart); d = DateUtils.setHours(d, 0);/*from w ww . j a va 2s. c om*/ d = DateUtils.setMinutes(d, 0); d = DateUtils.setSeconds(d, 0); d = DateUtils.setMilliseconds(d, 0); for (long mark = d.getTime(); mark <= pEnd; mark += DateUtils.MILLIS_PER_HOUR) { int markerPos = Math.round((mark - pStart) / DateUtils.MILLIS_PER_MINUTE); pG2D.setColor(Color.YELLOW); pG2D.fillRect(markerPos, 20, 2, 10); pG2D.setColor(Color.WHITE); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f)); pG2D.fillRect(markerPos - 5, 15, 12, 10); pG2D.setColor(Color.BLACK); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(mark)); NumberFormat f = NumberFormat.getNumberInstance(); f.setMinimumIntegerDigits(2); f.setMaximumFractionDigits(2); pG2D.drawString(f.format(cal.get(Calendar.HOUR_OF_DAY)), markerPos - 5, 23); } long currentDay = d.getTime(); while (currentDay < pEnd) { currentDay += DateUtils.MILLIS_PER_DAY; int markerPos = Math.round((currentDay - pStart) / DateUtils.MILLIS_PER_MINUTE); pG2D.setColor(new Color(123, 123, 123)); pG2D.fillRect(markerPos, 15, 3, 30); SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy"); String dayLabel = f.format(currentDay); Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(dayLabel, pG2D); pG2D.setColor(Color.YELLOW); int labelWidth = (int) labelBounds.getWidth() + 5; pG2D.fillRect(markerPos - (int) Math.rint(labelWidth / 2), 15, labelWidth, 10); pG2D.setColor(Color.BLACK); pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f)); pG2D.drawString(dayLabel, markerPos - (int) Math.rint(labelWidth / 2) + 2, 23); } }
From source file:org.csml.tommo.sugar.modules.MappingQuality.java
private void writeImage2HTML(HTMLReportArchive report, LaneCoordinates laneCoordinates, TileNumeration tileNumeration) throws IOException { final MappingQualityTableModel model = new MappingQualityTableModel(this, laneCoordinates, tileNumeration); ZipOutputStream zip = report.zipFile(); StringBuffer b = report.htmlDocument(); StringBuffer d = report.dataDocument(); int imgSize = Options.getHeatmapImageSize() + 1; // add one pixel for internal grid int width = imgSize * model.getColumnCount() + 1; // add one pixel for left border int topBottomSeparator = 50; if (model.getTopBottomSeparatorColumn() > 0) { width += topBottomSeparator; // add top bottom separator }/* www . j a v a2 s. c o m*/ int height = imgSize * model.getRowCount() + 1; // add one pixel for top border int yOffset = 10 * model.getTileNumeration().getCycleSize(); // space for column header int xOffset = 50; // space for row header BufferedImage fullImage = new BufferedImage(width + xOffset, height + yOffset, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) fullImage.getGraphics(); Color headerBackground = new Color(0x00, 0x00, 0x80); Color headerForeground = Color.WHITE; // Do the headers d.append("#Tiles: "); d.append("\t"); g2.setColor(headerBackground); g2.fillRect(0, height, width + xOffset, yOffset); g2.fillRect(width, 0, xOffset, height + yOffset); g2.setColor(headerForeground); g2.setFont(g2.getFont().deriveFont(7f).deriveFont(Font.BOLD)); drawColumnHeader(g2, model, imgSize, topBottomSeparator, height, d); g2.setFont(g2.getFont().deriveFont(9f).deriveFont(Font.BOLD)); drawRowHeader(g2, model, imgSize, width, xOffset); long before = System.currentTimeMillis(); for (int r = 0; r < model.getRowCount(); r++) { int separator = 0; for (int c = 0; c < model.getColumnCount(); c++) { TileCoordinates tileCoordinate = model.getCoordinateAt(r, c); MappingQualityMatrix matrix = getMeanQualityMatrix(tileCoordinate); if (matrix != null) { if (r < MappingQualityMatrix.THRESHOLDS.length) { ColorPaintScale paintScale = MappingQualityCellRenderer.getThresholdPaintScale(); BufferedImage image = (BufferedImage) matrix .createBufferedImageForThreshold(MappingQualityMatrix.THRESHOLDS[r], paintScale); g2.drawImage(image, 1 + imgSize * c + separator, 1 + imgSize * r, imgSize * (c + 1) + separator, imgSize * (r + 1), 0, 0, image.getWidth(), image.getHeight(), null); } else { ColorPaintScale paintScale = MappingQualityCellRenderer.getAveragePaintScale(); BufferedImage image = (BufferedImage) matrix.createBufferedImage(paintScale); g2.drawImage(image, 1 + imgSize * c + separator, 1 + imgSize * r, imgSize * (c + 1) + separator, imgSize * (r + 1), 0, 0, image.getWidth(), image.getHeight(), null); } } else { d.append("Missing matrix for: " + tileCoordinate + "\n"); } if (c == model.getTopBottomSeparatorColumn()) { separator = topBottomSeparator; } } } g2.dispose(); String imgFileName = "quality_matrix_" + laneCoordinates.getFlowCell() + "_" + laneCoordinates.getLane() + ".png"; zip.putNextEntry(new ZipEntry(report.folderName() + "/Images/" + imgFileName)); ImageIO.write(fullImage, "png", zip); b.append("<img src=\"Images/" + imgFileName + "\" alt=\"full image\">\n"); long after = System.currentTimeMillis(); d.append("Creating report time: " + (after - before)); }
From source file:net.java.sip.communicator.impl.osdependent.jdic.SystrayServiceJdicImpl.java
private BufferedImage createOverlayImage(String text) { int size = 16; BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //background/*from w w w . j a va2 s .c o m*/ g.setPaint(new Color(0, 0, 0, 102)); g.fillRoundRect(0, 0, size, size, size, size); //filling int mainRadius = 14; g.setPaint(new Color(255, 98, 89)); g.fillRoundRect(size / 2 - mainRadius / 2, size / 2 - mainRadius / 2, mainRadius, mainRadius, size, size); //text Font font = g.getFont(); g.setFont(new Font(font.getName(), Font.BOLD, 9)); FontMetrics fontMetrics = g.getFontMetrics(); int textWidth = fontMetrics.stringWidth(text); g.setColor(Color.white); g.drawString(text, size / 2 - textWidth / 2, size / 2 - fontMetrics.getHeight() / 2 + fontMetrics.getAscent()); return image; }
From source file:com.rapidminer.gui.plotter.charts.DistributionPlotter.java
@Override public void updatePlotter() { JFreeChart chart = null;// w w w .ja v a 2 s . c om Attribute attr = null; if (plotColumn != -1 && createFromModel) { attr = model.getTrainingHeader().getAttributes().get(model.getAttributeNames()[plotColumn]); } if (attr != null && attr.isNominal() && attr.getMapping().getValues().size() > MAX_NUMBER_OF_DIFFERENT_NOMINAL_VALUES) { // showing no chart because of too many different values chart = new JFreeChart(new Plot() { private static final long serialVersionUID = 1L; @Override public String getPlotType() { return "empty"; } @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { String msg = I18N.getGUILabel("plotter_panel.too_many_nominals", "Distribution Plotter", DistributionPlotter.MAX_NUMBER_OF_DIFFERENT_NOMINAL_VALUES); g2.setColor(Color.BLACK); g2.setFont(g2.getFont().deriveFont(g2.getFont().getSize() * 1.35f)); g2.drawChars(msg.toCharArray(), 0, msg.length(), 50, (int) (area.getHeight() / 2 + 0.5d)); } }); AbstractChartPanel panel = getPlotterPanel(); // Chart Panel Settings if (panel == null) { panel = createPanel(chart); } else { panel.setChart(chart); } // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!! panel.getChartRenderingInfo().setEntityCollection(null); } else { preparePlots(); if (!createFromModel && (groupColumn < 0 || plotColumn < 0)) { CategoryDataset dataset = new DefaultCategoryDataset(); chart = ChartFactory.createBarChart(null, // chart title "Not defined", // x axis label RANGE_AXIS_NAME, // y axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend true, // tooltips false // urls ); } else { try { if (model.isDiscrete(translateToModelColumn(plotColumn))) { chart = createNominalChart(); } else { chart = createNumericalChart(); } } catch (Exception e) { // do nothing - just do not draw the chart } } if (chart != null) { chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customization... Plot commonPlot = chart.getPlot(); commonPlot.setBackgroundPaint(Color.WHITE); if (commonPlot instanceof XYPlot) { XYPlot plot = (XYPlot) commonPlot; plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); // domain axis if (dataTable != null) { if (dataTable.isDate(plotColumn) || dataTable.isDateTime(plotColumn)) { DateAxis domainAxis = new DateAxis(dataTable.getColumnName(plotColumn)); domainAxis.setTimeZone(com.rapidminer.tools.Tools.getPreferredTimeZone()); plot.setDomainAxis(domainAxis); } else { NumberAxis numberAxis = new NumberAxis(dataTable.getColumnName(plotColumn)); plot.setDomainAxis(numberAxis); } } plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD); plot.getDomainAxis().setTickLabelFont(LABEL_FONT); plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD); plot.getRangeAxis().setTickLabelFont(LABEL_FONT); // ranging if (dataTable != null) { Range range = getRangeForDimension(plotColumn); if (range != null) { plot.getDomainAxis().setRange(range, true, false); } range = getRangeForName(RANGE_AXIS_NAME); if (range != null) { plot.getRangeAxis().setRange(range, true, false); } } // rotate labels if (isLabelRotating()) { plot.getDomainAxis().setTickLabelsVisible(true); plot.getDomainAxis().setVerticalTickLabels(true); } } else if (commonPlot instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) commonPlot; plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD); plot.getRangeAxis().setTickLabelFont(LABEL_FONT); plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD); plot.getDomainAxis().setTickLabelFont(LABEL_FONT); } // legend settings LegendTitle legend = chart.getLegend(); if (legend != null) { legend.setPosition(RectangleEdge.TOP); legend.setFrame(BlockBorder.NONE); legend.setHorizontalAlignment(HorizontalAlignment.LEFT); legend.setItemFont(LABEL_FONT); } AbstractChartPanel panel = getPlotterPanel(); // Chart Panel Settings if (panel == null) { panel = createPanel(chart); } else { panel.setChart(chart); } // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!! panel.getChartRenderingInfo().setEntityCollection(null); } } }
From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java
private byte[] createImage(int width, int height, String text) throws IOException { if (width < 0) { width = random.nextInt(DEFAULT_MAX_IMAGE_WIDTH - DEFAULT_MIN_IMAGE_WIDTH) + DEFAULT_MIN_IMAGE_WIDTH; }//from www. jav a2s .c o m if (height < 0) { height = random.nextInt(DEFAULT_MAX_IMAGE_HEIGHT - DEFAULT_MIN_IMAGE_HEIGHT) + DEFAULT_MIN_IMAGE_HEIGHT; } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D) img.getGraphics(); g2.setBackground(new Color(220, 220, 220)); Dimension size; float fontSize = g2.getFont().getSize(); // Make the text as large as possible. do { g2.setFont(g2.getFont().deriveFont(fontSize)); FontMetrics metrics = g2.getFontMetrics(g2.getFont()); int hgt = metrics.getHeight(); int adv = metrics.stringWidth(text); size = new Dimension(adv + 2, hgt + 2); fontSize = fontSize + 1f; } while (size.width < Math.round(0.9 * width) && size.height < Math.round(0.9 * height)); g2.setColor(Color.DARK_GRAY); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.drawString(text, (width - size.width) / 2, (height - size.height) / 2); g2.setColor(Color.LIGHT_GRAY); g2.drawRect(0, 0, width - 1, height - 1); ByteArrayOutputStream baos = new ByteArrayOutputStream(width * height); ImageIO.write(img, "png", baos); baos.flush(); byte[] rawBytes = baos.toByteArray(); baos.close(); return rawBytes; }
From source file:org.optaplanner.examples.coachshuttlegathering.swingui.CoachShuttleGatheringWorldPanel.java
public void resetPanel(CoachShuttleGatheringSolution solution) { translator = new LatitudeLongitudeTranslator(); for (RoadLocation location : solution.getLocationList()) { translator.addCoordinates(location.getLatitude(), location.getLongitude()); }/* w ww . j av a2 s . co m*/ Dimension size = getSize(); double width = size.getWidth(); double height = size.getHeight(); translator.prepareFor(width, height); Graphics2D g = createCanvas(width, height); g.setColor(TangoColorFactory.ORANGE_3); RoadLocation hubLocation = solution.getHub().getLocation(); translator.drawSquare(g, hubLocation.getLongitude(), hubLocation.getLatitude(), 5); for (BusStop stop : solution.getStopList()) { RoadLocation location = stop.getLocation(); g.setColor((stop.getPassengerQuantity() <= 0) ? TangoColorFactory.ALUMINIUM_4 : (stop.getTransportTimeToHub() == null) ? TangoColorFactory.ORANGE_2 : (stop.getTransportTimeRemainder() < 0) ? TangoColorFactory.SCARLET_2 : TangoColorFactory.ORANGE_2); translator.drawSquare(g, location.getLongitude(), location.getLatitude(), 3, stop.getTransportLabel()); } List<Bus> busList = solution.getBusList(); g.setColor(TangoColorFactory.ALUMINIUM_2); g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE)); for (Bus bus : busList) { RoadLocation location = bus.getLocation(); g.setColor(bus instanceof Coach ? TangoColorFactory.ORANGE_1 : TangoColorFactory.ALUMINIUM_2); translator.drawSquare(g, location.getLongitude(), location.getLatitude(), 3, StringUtils.abbreviate(bus.getName(), 20)); } int colorIndex = 0; for (Bus bus : busList) { g.setColor(TangoColorFactory.SEQUENCE_2[colorIndex]); BusStop lastStop = null; for (BusStop stop = bus.getNextStop(); stop != null; stop = stop.getNextStop()) { RoadLocation previousLocation = stop.getPreviousBusOrStop().getLocation(); RoadLocation location = stop.getLocation(); translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(), location.getLongitude(), location.getLatitude(), false, false); lastStop = stop; } if (lastStop != null || bus instanceof Coach) { RoadLocation lastStopLocation = lastStop == null ? bus.getLocation() : lastStop.getLocation(); StopOrHub destination = bus.getDestination(); if (destination != null) { RoadLocation destinationLocation = destination.getLocation(); translator.drawRoute(g, lastStopLocation.getLongitude(), lastStopLocation.getLatitude(), destinationLocation.getLongitude(), destinationLocation.getLatitude(), false, true); } } colorIndex = (colorIndex + 1) % TangoColorFactory.SEQUENCE_2.length; } repaint(); }
From source file:gg.msn.ui.panel.MainPanel.java
@Override public void paint(Graphics g) { super.paint(g); try {// w ww . ja v a2 s . c om Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //render per utenti Facebook if (ChatClientView.protocol.equals(ChatClientView.FACEBOOK_PROTOCOL)) { final FacebookUser user = (FacebookUser) value; int textY = (getHeight() / 2) + (g2.getFont().getSize() / 2); //name string g2.setFont(list.getFont()); g2.drawString(user.name, WHITE_SPACE + IMAGE_LATE + 3, textY); //status string // g2.setFont(list.getFont()); // g2.drawString(user.status, WHITE_SPACE + IMAGE_LATE + 3, textY); //icon ImageIcon icon = user.portrait; //log.debug("icon [" + icon + "]"); //ImageIcon scaledIcon = new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_AREA_AVERAGING)); g2.drawImage(icon.getImage(), WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, null); // g2.setColor(Color.WHITE); // g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, ARC_SIZE, ARC_SIZE); // g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - ((IMAGE_LATE+1) / 2), IMAGE_LATE+1, IMAGE_LATE+1, ARC_SIZE, ARC_SIZE); // g2.drawRoundRect(WHITE_SPACE, getHeight() / 2 - ((IMAGE_LATE+2) / 2), IMAGE_LATE+2, IMAGE_LATE+2, ARC_SIZE, ARC_SIZE); //render per utenti Client // log.debug("user status [" + user.status + "]"); // log.debug("user online status [" + user.onlineStatus + "]"); if (StringUtils.equals(user.status, FacebookUser.STATUS_ONLINE)) { g2.setColor(Color.GREEN); g2.fillOval(getWidth() - STATUS_ICON_OFFSET, (getHeight() / 2) - (STATUS_ICON_WIDTH / 2), STATUS_ICON_WIDTH, STATUS_ICON_WIDTH); } else { g2.setColor(Color.GRAY); g2.fillOval(getWidth() - STATUS_ICON_OFFSET, (getHeight() / 2) - (STATUS_ICON_WIDTH / 2), STATUS_ICON_WIDTH, STATUS_ICON_WIDTH); } } else { g2.setFont(list.getFont()); int textY = (getHeight() / 2) + (g2.getFont().getSize() / 2); Client client = (Client) value; // setText((client).getNick()); ImageIcon icon = null; try { new ImageIcon(client.getImage()); } catch (Exception e) { // log.debug("immgine non presente"); icon = ThemeManager.getTheme().get(ThemeManager.USER_ICON); } g2.drawString(client.getNick(), WHITE_SPACE + IMAGE_LATE + 3, textY); //log.debug("icon [" + icon + "]"); //ImageIcon scaledIcon = new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_AREA_AVERAGING)); g2.drawImage(icon.getImage(), WHITE_SPACE, getHeight() / 2 - (IMAGE_LATE / 2), IMAGE_LATE, IMAGE_LATE, null); // setFont(list.getFont()); // setIcon(scaledIcon); } } catch (Exception e) { log.warn(e); } }
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 w w . j av a2 s.co m*/ 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.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void updateInvestInformationBox(Graphics2D g2) { 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 Activities activities = this.investmentFlowChartJDialog.getInvestActivities(this.investPointIndex); this.investValues.clear(); this.investParams.clear(); this.totalInvestValue = 0.0; final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); for (int i = 0, size = activities.size(); i < size; i++) { final Activity activity = activities.get(i); // Buy only. this.investParams.add(activity.getType() + " " + org.yccheok.jstock.portfolio.Utils.toQuantity(activity.get(Activity.Param.Quantity)) + " " + ((StockInfo) activity.get(Activity.Param.StockInfo)).symbol); if (activity.getType() == Activity.Type.Buy) { final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); final double amount = convertToPoundIfNecessary(stockInfo.code, activity.getAmount()); this.totalInvestValue += amount; this.investValues .add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else {// www .j a v a 2 s.co m assert (false); } } final boolean isTotalNeeded = this.investParams.size() > 1; final String totalParam = GUIBundle.getString("InvestmentFlowLayerUI_Total_Invest"); final String totalValue = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, this.totalInvestValue); /* This is the height for "total" information. */ int totalHeight = 0; assert (this.investValues.size() == this.investParams.size()); int index = 0; final int paramValueWidthMargin = 10; final int paramValueHeightMargin = 0; int maxInfoWidth = -1; // paramFontMetrics will always "smaller" than valueFontMetrics. int totalInfoHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * this.investValues.size() + paramValueHeightMargin * (this.investValues.size() - 1); for (String param : this.investParams) { final String value = this.investValues.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(param + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(value); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } if (isTotalNeeded) { final int tmp = paramFontMetrics.stringWidth(totalParam + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(totalValue); if (maxInfoWidth < tmp) { maxInfoWidth = tmp; } totalHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()); } final Date date = activities.getDate().getTime(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy"); final String dateString = simpleDateFormat.format(date); final int dateStringWidth = dateFontMetrics.stringWidth(dateString); final int dateStringHeight = dateFontMetrics.getHeight(); final int maxStringWidth = Math.max(dateStringWidth, maxInfoWidth); final int dateInfoHeightMargin = 5; final int infoTotalHeightMargin = 5; final int maxStringHeight = isTotalNeeded ? (dateStringHeight + dateInfoHeightMargin + totalInfoHeight + infoTotalHeightMargin + totalHeight) : (dateStringHeight + dateInfoHeightMargin + totalInfoHeight); // Now, We have a pretty good information on maxStringWidth and maxStringHeight. final int padding = 5; final int boxPointMargin = 8; final int width = maxStringWidth + (padding << 1); final int height = maxStringHeight + (padding << 1); // On left side of the ball. final int suggestedX = (int) (this.investPoint.getX() - width - boxPointMargin); final int suggestedY = (int) (this.investPoint.getY() - (height >> 1)); final int x = suggestedX > this.drawArea.getX() ? (suggestedX + width) < (this.drawArea.getX() + this.drawArea.getWidth()) ? suggestedX : (int) (this.drawArea.getX() + this.drawArea.getWidth() - width - boxPointMargin) : (int) (investPoint.getX() + boxPointMargin); final int y = suggestedY > this.drawArea.getY() ? (suggestedY + height) < (this.drawArea.getY() + this.drawArea.getHeight()) ? suggestedY : (int) (this.drawArea.getY() + this.drawArea.getHeight() - height - boxPointMargin) : (int) (this.drawArea.getY() + boxPointMargin); this.investRect.setRect(x, y, width, height); }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void updateROIInformationBox(Graphics2D g2) { 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 Activities activities = this.investmentFlowChartJDialog.getROIActivities(this.ROIPointIndex); this.ROIValues.clear(); this.ROIParams.clear(); this.totalROIValue = 0.0; final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); for (int i = 0, size = activities.size(); i < size; i++) { final Activity activity = activities.get(i); // Buy, Sell or Dividend only. if (activity.getType() == Activity.Type.Buy) { final double quantity = (Double) activity.get(Activity.Param.Quantity); final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); this.ROIParams.add(GUIBundle.getString("InvestmentFlowLayerUI_Own") + " " + org.yccheok.jstock.portfolio.Utils.toQuantity(quantity) + " " + stockInfo.symbol); final double amount = convertToPoundIfNecessary(stockInfo.code, quantity * this.investmentFlowChartJDialog.getStockPrice(stockInfo.code)); this.totalROIValue += amount; this.ROIValues.add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else if (activity.getType() == Activity.Type.Sell) { final double quantity = (Double) activity.get(Activity.Param.Quantity); final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); this.ROIParams.add(activity.getType() + " " + org.yccheok.jstock.portfolio.Utils.toQuantity(quantity) + " " + stockInfo.symbol); final double amount = convertToPoundIfNecessary(stockInfo.code, activity.getAmount()); this.totalROIValue += amount; this.ROIValues.add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else if (activity.getType() == Activity.Type.Dividend) { final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); this.ROIParams.add(activity.getType() + " " + stockInfo.symbol); final double amount = activity.getAmount(); this.totalROIValue += amount; this.ROIValues.add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else {/* w ww . j a va2 s . co m*/ assert (false); } } final boolean isTotalNeeded = this.ROIParams.size() > 1; final String totalParam = GUIBundle.getString("InvestmentFlowLayerUI_Total_Return"); final String totalValue = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, this.totalROIValue); /* This is the height for "total" information. */ int totalHeight = 0; assert (this.ROIParams.size() == this.ROIValues.size()); int index = 0; final int paramValueWidthMargin = 10; final int paramValueHeightMargin = 0; int maxInfoWidth = -1; // paramFontMetrics will always "smaller" than valueFontMetrics. int totalInfoHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * this.ROIValues.size() + paramValueHeightMargin * (this.ROIValues.size() - 1); for (String param : this.ROIParams) { final String value = this.ROIValues.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(param + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(value); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } if (isTotalNeeded) { final int tmp = paramFontMetrics.stringWidth(totalParam + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(totalValue); if (maxInfoWidth < tmp) { maxInfoWidth = tmp; } totalHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()); } final Date date = activities.getDate().getTime(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy"); final String dateString = simpleDateFormat.format(date); final int dateStringWidth = dateFontMetrics.stringWidth(dateString); final int dateStringHeight = dateFontMetrics.getHeight(); final int maxStringWidth = Math.max(dateStringWidth, maxInfoWidth); final int dateInfoHeightMargin = 5; final int infoTotalHeightMargin = 5; final int maxStringHeight = isTotalNeeded ? (dateStringHeight + dateInfoHeightMargin + totalInfoHeight + infoTotalHeightMargin + totalHeight) : (dateStringHeight + dateInfoHeightMargin + totalInfoHeight); // Now, We have a pretty good information on maxStringWidth and maxStringHeight. final int padding = 5; final int boxPointMargin = 8; final int width = maxStringWidth + (padding << 1); final int height = maxStringHeight + (padding << 1); final int borderWidth = width + 2; final int borderHeight = height + 2; // On left side of the ball. final double suggestedBorderX = this.ROIPoint.getX() - borderWidth - boxPointMargin; final double suggestedBorderY = this.ROIPoint.getY() - (borderHeight >> 1); final double bestBorderX = suggestedBorderX > this.drawArea.getX() ? (suggestedBorderX + borderWidth) < (this.drawArea.getX() + this.drawArea.getWidth()) ? suggestedBorderX : this.drawArea.getX() + this.drawArea.getWidth() - borderWidth - boxPointMargin : this.ROIPoint.getX() + boxPointMargin; final double bestBorderY = suggestedBorderY > this.drawArea.getY() ? (suggestedBorderY + borderHeight) < (this.drawArea.getY() + this.drawArea.getHeight()) ? suggestedBorderY : this.drawArea.getY() + this.drawArea.getHeight() - borderHeight - boxPointMargin : this.drawArea.getY() + boxPointMargin; final double x = bestBorderX + 1; final double y = bestBorderY + 1; this.ROIRect.setRect(x, y, width, height); }