List of usage examples for java.awt Graphics2D getFontMetrics
public abstract FontMetrics getFontMetrics(Font f);
From source file:org.executequery.gui.erd.ErdTable.java
protected void drawTable(Graphics2D g, int offsetX, int offsetY) { if (parent == null) { return;/* w w w . ja va2 s. c o 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.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);/* www. ja v a 2 s .c o 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:org.yccheok.jstock.gui.charting.ChartLayerUI.java
private void drawInformationBox(Graphics2D g2, JXLayer<? extends V> layer) { if (JStock.instance().getJStockOptions() .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Hide) { return;// ww w . ja v a2 s . c o m } 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 List<ChartData> chartDatas = this.chartJDialog.getChartDatas(); List<String> values = new ArrayList<String>(); final ChartData chartData = chartDatas.get(this.mainTraceInfo.getDataIndex()); // Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. // If multiple threads access a format concurrently, it must be synchronized externally. // http://stackoverflow.com/questions/2213410/usage-of-decimalformat-for-the-following-case final DecimalFormat integerFormat = new DecimalFormat("###,###"); // It is common to use OHLC for chat, instead of using PrevPrice. values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.openPrice)); values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.highPrice)); values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.lowPrice)); values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.lastPrice)); values.add(integerFormat.format(chartData.volume)); final List<String> indicatorParams = new ArrayList<String>(); final List<String> indicatorValues = new ArrayList<String>(); final DecimalFormat decimalFormat = new DecimalFormat("0.00"); for (TraceInfo indicatorTraceInfo : this.indicatorTraceInfos) { final int plotIndex = indicatorTraceInfo.getPlotIndex(); final int seriesIndex = indicatorTraceInfo.getSeriesIndex(); final int dataIndex = indicatorTraceInfo.getDataIndex(); final String name = this.getLegendName(plotIndex, seriesIndex); final Number value = this.getValue(plotIndex, seriesIndex, dataIndex); if (name == null || value == null) { continue; } indicatorParams.add(name); indicatorValues.add(decimalFormat.format(value)); } assert (values.size() == params.size()); int index = 0; final int paramValueWidthMargin = 10; final int paramValueHeightMargin = 0; // Slightly larger than dateInfoHeightMargin, as font for indicator is // larger than date's. final int infoIndicatorHeightMargin = 8; int maxInfoWidth = -1; // paramFontMetrics will always "smaller" than valueFontMetrics. int totalInfoHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * values.size() + paramValueHeightMargin * (values.size() - 1); for (String param : params) { final String value = values.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(param + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(value); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } if (indicatorValues.size() > 0) { totalInfoHeight += infoIndicatorHeightMargin; totalInfoHeight += Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * indicatorValues.size() + paramValueHeightMargin * (indicatorValues.size() - 1); index = 0; for (String indicatorParam : indicatorParams) { final String indicatorValue = indicatorValues.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(indicatorParam + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(indicatorValue); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } } final Date date = new Date(chartData.timestamp); // Date formats are not synchronized. It is recommended to create separate format instances for each thread. // If multiple threads access a format concurrently, it must be synchronized externally. final SimpleDateFormat simpleDateFormat = this.simpleDataFormatThreadLocal.get(); final String dateString = simpleDateFormat.format(date); final int dateStringWidth = dateFontMetrics.stringWidth(dateString); final int dateStringHeight = dateFontMetrics.getHeight(); // We want to avoid information box from keep changing its width while // user moves along the mouse. This will prevent user from feeling, // information box is flickering, which is uncomfortable to user's eye. final int maxStringWidth = Math.max(dateFontMetrics.stringWidth(longDateString), Math.max(this.maxWidth, Math.max(dateStringWidth, maxInfoWidth))); if (maxStringWidth > this.maxWidth) { this.maxWidth = maxStringWidth; } final int dateInfoHeightMargin = 5; final int maxStringHeight = dateStringHeight + dateInfoHeightMargin + totalInfoHeight; final int padding = 5; final int boxPointMargin = 8; final int width = maxStringWidth + (padding << 1); final int height = maxStringHeight + (padding << 1); /* Get Border Rect Information. */ /* fillRect(1, 1, 1, 1); // O is rect pixel xxx xOx xxx drawRect(0, 0, 2, 2); // O is rect pixel OOO OxO OOO */ final int borderWidth = width + 2; final int borderHeight = height + 2; // On left side of the ball. final double suggestedBorderX = this.mainTraceInfo.getPoint().getX() - borderWidth - boxPointMargin; final double suggestedBorderY = this.mainTraceInfo.getPoint().getY() - (borderHeight >> 1); double bestBorderX = 0; double bestBorderY = 0; if (JStock.instance().getJStockOptions() .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Stay) { if (this.mainTraceInfo.getPoint() .getX() > ((int) (this.mainDrawArea.getX() + this.mainDrawArea.getWidth() + 0.5) >> 1)) { bestBorderX = this.mainDrawArea.getX(); bestBorderY = this.mainDrawArea.getY(); } else { bestBorderX = this.mainDrawArea.getX() + this.mainDrawArea.getWidth() - borderWidth; bestBorderY = this.mainDrawArea.getY(); } } else { assert (JStock.instance().getJStockOptions() .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Follow); bestBorderX = suggestedBorderX > this.mainDrawArea.getX() ? (suggestedBorderX + borderWidth) < (this.mainDrawArea.getX() + this.mainDrawArea.getWidth()) ? suggestedBorderX : this.mainDrawArea.getX() + this.mainDrawArea.getWidth() - borderWidth - boxPointMargin : this.mainTraceInfo.getPoint().getX() + boxPointMargin; bestBorderY = suggestedBorderY > this.mainDrawArea.getY() ? (suggestedBorderY + borderHeight) < (this.mainDrawArea.getY() + this.mainDrawArea.getHeight()) ? suggestedBorderY : this.mainDrawArea.getY() + this.mainDrawArea.getHeight() - borderHeight - boxPointMargin : this.mainDrawArea.getY() + boxPointMargin; } final double x = bestBorderX + 1; final double y = bestBorderY + 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); g2.drawRoundRect((int) (bestBorderX + 0.5), (int) (bestBorderY + 0.5), borderWidth - 1, borderHeight - 1, 15, 15); g2.setColor(COLOR_BACKGROUND); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect((int) (x + 0.5), (int) (y + 0.5), width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); int yy = (int) (y + padding + dateFontMetrics.getAscent() + 0.5); g2.setFont(dateFont); g2.setColor(COLOR_BLUE); g2.drawString(dateString, (int) (((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x + 0.5), yy); index = 0; yy += dateFontMetrics.getDescent() + dateInfoHeightMargin + valueFontMetrics.getAscent(); final String CLOSE_STR = GUIBundle.getString("StockHistory_Close"); for (String param : params) { final String value = values.get(index++); g2.setColor(Color.BLACK); if (param.equals(CLOSE_STR)) { // It is common to use OHLC for chat, instead of using PrevPrice. final double changePrice = chartData.lastPrice - chartData.openPrice; if (changePrice > 0.0) { g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR); } else if (changePrice < 0.0) { g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR); } } g2.setFont(paramFont); g2.drawString(param + ":", (int) (padding + x + 0.5), yy); g2.setFont(valueFont); g2.drawString(value, (int) (width - padding - valueFontMetrics.stringWidth(value) + x + 0.5), yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + valueFontMetrics.getHeight(); } g2.setColor(Color.BLACK); yy -= paramValueHeightMargin; yy += infoIndicatorHeightMargin; index = 0; for (String indicatorParam : indicatorParams) { final String indicatorValue = indicatorValues.get(index++); g2.setFont(paramFont); g2.drawString(indicatorParam + ":", (int) (padding + x + 0.5), yy); g2.setFont(valueFont); g2.drawString(indicatorValue, (int) (width - padding - valueFontMetrics.stringWidth(indicatorValue) + x + 0.5), yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + valueFontMetrics.getHeight(); } g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:edu.ku.brc.af.ui.forms.validation.ValFormattedTextField.java
/** * Creates the various UI Components for the formatter. *//*from w ww. j av a2 s. c om*/ protected void createUI() { CellConstraints cc = new CellConstraints(); if (isViewOnly || (formatter != null && !formatter.isUserInputNeeded() && fields != null && fields.size() == 1)) { viewtextField = new JTextField(); setControlSize(viewtextField); // Remove by rods 12/5/08 this messes thihngs up // values don't get inserted correctly, shouldn't be needed anyway //JFormattedDoc document = new JFormattedDoc(viewtextField, formatter, formatter.getFields().get(0)); //viewtextField.setDocument(document); //document.addDocumentListener(this); //documents.add(document); ViewFactory.changeTextFieldUIForDisplay(viewtextField, false); PanelBuilder builder = new PanelBuilder(new FormLayout("1px,f:p:g,1px", "1px,f:p:g,1px"), this); builder.add(viewtextField, cc.xy(2, 2)); bgColor = viewtextField.getBackground(); } else { JTextField txt = new JTextField(); Font txtFont = txt.getFont(); Font font = new Font("Courier", Font.PLAIN, txtFont.getSize()); BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.setFont(font); FontMetrics fm = g.getFontMetrics(font); g.dispose(); Insets ins = txt.getBorder().getBorderInsets(txt); int baseWidth = ins.left + ins.right; bgColor = txt.getBackground(); StringBuilder sb = new StringBuilder("1px"); for (UIFieldFormatterField f : fields) { sb.append(","); if (f.getType() == FieldType.separator || f.getType() == FieldType.constant) { sb.append('p'); } else { sb.append(((fm.getMaxAdvance() * f.getSize()) + baseWidth) + "px"); } } sb.append(",1px"); PanelBuilder builder = new PanelBuilder(new FormLayout(sb.toString(), "1px,P:G,1px"), this); comps = new JComponent[fields.size()]; int inx = 0; for (UIFieldFormatterField f : fields) { JComponent comp = null; JComponent tfToAdd = null; if (f.getType() == FieldType.separator || f.getType() == FieldType.constant) { comp = createLabel(f.getValue()); if (f.getType() == FieldType.constant) { comp.setBackground(Color.WHITE); comp.setOpaque(true); } tfToAdd = comp; } else { JTextField tf = new BGTextField(f.getSize(), isViewOnly ? "" : f.getValue()); tfToAdd = tf; if (inx == 0) { tf.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { checkForPaste(e); } }); } JFormattedDoc document = new JFormattedDoc(tf, formatter, f); tf.setDocument(document); document.addDocumentListener(new DocumentAdaptor() { @Override protected void changed(DocumentEvent e) { isChanged = true; if (!shouldIgnoreNotifyDoc) { String fldStr = getText(); int len = StringUtils.isNotEmpty(fldStr) ? fldStr.length() : 0; if (formatter != null && len > 0 && formatter.isLengthOK(len)) { setState(formatter.isValid(fldStr) ? UIValidatable.ErrorType.Valid : UIValidatable.ErrorType.Error); repaint(); } //validateState(); if (changeListener != null) { changeListener.stateChanged(new ChangeEvent(this)); } if (documentListeners != null) { for (DocumentListener dl : documentListeners) { dl.changedUpdate(null); } } } currCachedValue = null; } }); documents.add(document); addFocusAdapter(tf); comp = tf; comp.setFont(font); if (f.isIncrementer()) { editTF = tf; cardLayout = new CardLayout(); cardPanel = new JPanel(cardLayout); cardPanel.add("edit", tf); viewTF = new BGTextField(f.getSize(), isViewOnly ? "" : f.getValue()); viewTF.setDocument(document); cardPanel.add("view", viewTF); cardLayout.show(cardPanel, "view"); comp = cardPanel; tfToAdd = cardPanel; } } setControlSize(tfToAdd); builder.add(comp, cc.xy(inx + 2, 2)); comps[inx] = tfToAdd; inx++; } } }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void drawTitle(Graphics2D g2) { final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Color oldColor = g2.getColor(); final Font oldFont = g2.getFont(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final Font titleFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() * 1.5f); final int margin = 5; final FontMetrics titleFontMetrics = g2.getFontMetrics(titleFont); final FontMetrics oldFontMetrics = g2.getFontMetrics(oldFont); final java.text.NumberFormat numberFormat = java.text.NumberFormat.getInstance(); numberFormat.setMaximumFractionDigits(2); numberFormat.setMinimumFractionDigits(2); final double totalInvestValue = this.investmentFlowChartJDialog.getTotalInvestValue(); final double totalROIValue = this.investmentFlowChartJDialog.getTotalROIValue(); final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); final String invest = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalInvestValue);/* w w w.j a va2 s . c om*/ final String roi = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalROIValue); final double gain = totalROIValue - totalInvestValue; final double percentage = totalInvestValue > 0.0 ? gain / totalInvestValue * 100.0 : 0.0; final String gain_str = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, gain); final String percentage_str = numberFormat.format(percentage); final String SELECTED = this.investmentFlowChartJDialog.getCurrentSelectedString(); final String INVEST = GUIBundle.getString("InvestmentFlowLayerUI_Invest"); final String RETURN = GUIBundle.getString("InvestmentFlowLayerUI_Return"); final String GAIN = (SELECTED.length() > 0 ? SELECTED + " " : "") + GUIBundle.getString("InvestmentFlowLayerUI_Gain"); final String LOSS = (SELECTED.length() > 0 ? SELECTED + " " : "") + GUIBundle.getString("InvestmentFlowLayerUI_Loss"); final int string_width = oldFontMetrics.stringWidth(INVEST + ": ") + titleFontMetrics.stringWidth(invest + " ") + oldFontMetrics.stringWidth(RETURN + ": ") + titleFontMetrics.stringWidth(roi + " ") + oldFontMetrics.stringWidth((gain >= 0 ? GAIN : LOSS) + ": ") + titleFontMetrics.stringWidth(gain_str + " (" + percentage_str + "%)"); int x = (int) (this.investmentFlowChartJDialog.getChartPanel().getWidth() - string_width) >> 1; final int y = margin + titleFontMetrics.getAscent(); g2.setFont(oldFont); g2.drawString(INVEST + ": ", x, y); x += oldFontMetrics.stringWidth(INVEST + ": "); g2.setFont(titleFont); g2.drawString(invest + " ", x, y); x += titleFontMetrics.stringWidth(invest + " "); g2.setFont(oldFont); g2.drawString(RETURN + ": ", x, y); x += oldFontMetrics.stringWidth(RETURN + ": "); g2.setFont(titleFont); g2.drawString(roi + " ", x, y); x += titleFontMetrics.stringWidth(roi + " "); g2.setFont(oldFont); if (gain >= 0) { if (gain > 0) { if (org.yccheok.jstock.engine.Utils.isFallBelowAndRiseAboveColorReverse()) { g2.setColor(JStock.instance().getJStockOptions().getLowerNumericalValueForegroundColor()); } else { g2.setColor(JStock.instance().getJStockOptions().getHigherNumericalValueForegroundColor()); } } g2.drawString(GAIN + ": ", x, y); x += oldFontMetrics.stringWidth(GAIN + ": "); } else { if (org.yccheok.jstock.engine.Utils.isFallBelowAndRiseAboveColorReverse()) { g2.setColor(JStock.instance().getJStockOptions().getHigherNumericalValueForegroundColor()); } else { g2.setColor(JStock.instance().getJStockOptions().getLowerNumericalValueForegroundColor()); } g2.drawString(LOSS + ": ", x, y); x += oldFontMetrics.stringWidth(LOSS + ": "); } g2.setFont(titleFont); g2.drawString(gain_str + " (" + percentage_str + "%)", x, y); g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private byte[] generateNoDataChart(int width, int height) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(parseColor(M_sm.getChartBackgroundColor())); g2d.clearRect(0, 0, width - 1, height - 1); g2d.setColor(parseColor("#cccccc")); g2d.drawRect(0, 0, width - 1, height - 1); Font f = new Font("SansSerif", Font.PLAIN, 12); g2d.setFont(f);//from www . ja va 2 s . c o m FontMetrics fm = g2d.getFontMetrics(f); String noData = msgs.getString("no_data"); int noDataWidth = fm.stringWidth(noData); int noDataHeight = fm.getHeight(); g2d.setColor(parseColor("#555555")); g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { LOG.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java
private byte[] generateNoDataChart(int width, int height) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(parseColor(statsManager.getChartBackgroundColor())); g2d.clearRect(0, 0, width - 1, height - 1); g2d.setColor(parseColor("#cccccc")); g2d.drawRect(0, 0, width - 1, height - 1); Font f = new Font("SansSerif", Font.PLAIN, 12); g2d.setFont(f);/*from w ww.j a va 2 s . c om*/ FontMetrics fm = g2d.getFontMetrics(f); String noData = msgs.getString("no_data"); int noDataWidth = fm.stringWidth(noData); int noDataHeight = fm.getHeight(); g2d.setColor(parseColor("#555555")); g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { log.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private void processTextElement(Graphics2D g2, Element textElement) { int x = Integer.valueOf(textElement.getAttributeValue("X")); int y = Integer.valueOf(textElement.getAttributeValue("Y")); int width = Integer.valueOf(textElement.getAttributeValue("Width")); int height = Integer.valueOf(textElement.getAttributeValue("Height")); String alignment = textElement.getAttributeValue("TextAlignment"); boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase()); boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias"); Font font = parseFont(textElement.getAttributeValue("Font")); logger.info("Using font " + font); // now get the textim4java performance String text = textElement.getAttributeValue("Text"); // if text matches pattern of %VARIABLE%{MODIFIER} logger.info("parsing token {}", text); Matcher matcher = pattern.matcher(text); int start = 0; while (matcher.find(start)) { // apply modification text = text.replace(matcher.group(), applyModifier(matcher.group())); start = matcher.end();//from w w w. j ava 2 s. c o m } BufferedImage tmpImage; if (width > 0 && height > 0) { // create a transparent tmpImage tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { FontMetrics fm = g2.getFontMetrics(font); Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds(); // we need to create a transparent image to paint tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_ARGB); } Graphics2D g2d = tmpImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); // } g2d.setFont(font); Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); g2d.setColor(textColor); Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f); g2d.setComposite(comp); drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); tmpImage = processActions(textElement, tmpImage); //// Graphics2D g2d = tmpImage.createGraphics(); // // set current font // g2.setFont(font); //// g2d.setComposite(AlphaComposite.Clear); //// g2d.fillRect(0, 0, width, height); //// g2d.setComposite(AlphaComposite.Src); // // TODO: we have to parse it // int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth")); // // the color of the outline // if (strokeWidth > 0) { //// Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor"))); //// AffineTransform affineTransform; //// affineTransform = g2d.getTransform(); //// affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2 //// + (outlineBounds.height / 2)); //// g2d.transform(affineTransform); //// // backup stroke width and color //// Stroke originalStroke = g2d.getStroke(); //// Color originalColor = g2d.getColor(); //// g2d.setColor(strokeColor); //// g2d.setStroke(new BasicStroke(strokeWidth)); //// g2d.draw(shape); //// g2d.setClip(shape); //// // restore stroke width and color //// g2d.setStroke(originalStroke); //// g2d.setColor(originalColor); // } //// // get the text color // Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); // g2.setColor(textColor); //// g2d.setBackground(Color.BLACK); //// g2d.setStroke(new BasicStroke(2)); //// g2d.setColor(Color.WHITE); // // draw the text // // drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline); // g2.drawString(text, x, y); // Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position // FontMetrics fm = g2.getFontMetrics(); // FontRenderContext frc = g2.getFontRenderContext(); // TextLayout tl = new TextLayout(text, g2.getFont(), frc); // AffineTransform transform = new AffineTransform(); // transform.setToTranslation(rect.getX(), rect.getY()); // if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) { // double scaleY // = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY() // - tl.getOutline(null).getBounds().getMinY()); // transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY); // } // Shape shape = tl.getOutline(transform); // g2.setClip(shape); // g2.fill(shape.getBounds()); // if (antiAlias) { // we need to restore antialias to none // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // } // g2.drawString(text, x, y); // alway resize // BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height); // tmpImage = scaleFilter.filter(tmpImage, null); // draw the image to the source g2.drawImage(tmpImage, x, y, width, height, null); try { ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png"); } catch (IOException ex) { } }
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 w w. j av a 2 s . 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:de.tor.tribes.ui.panels.MinimapPanel.java
private boolean redraw() { Village[][] mVisibleVillages = DataHolder.getSingleton().getVillages(); if (mVisibleVillages == null || mBuffer == null) { return false; }// ww w . ja v 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; }