List of usage examples for java.awt Graphics2D getRenderingHint
public abstract Object getRenderingHint(Key hintKey);
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);/*from w w w . j a va 2 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.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
@Override protected void paintLayer(Graphics2D g2, JXLayer<? extends V> layer) { super.paintLayer(g2, layer); final ChartPanel chartPanel = ((ChartPanel) layer.getView()); final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea(); this.drawArea.setRect(_plotArea); if (false == this.investmentFlowChartJDialog.isFinishLookUpPrice()) { this.drawBusyBox(g2, layer); }/*from w w w. j ava 2 s. co m*/ if (this.investPoint != null) { final int RADIUS = 8; final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(COLOR_RED); g2.fillOval((int) (this.investPoint.getX() - (RADIUS >> 1) + 0.5), (int) (this.investPoint.getY() - (RADIUS >> 1) + 0.5), RADIUS, RADIUS); g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); this.updateInvestInformationBox(g2); } if (this.ROIPoint != null) { final int RADIUS = 8; final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(COLOR_BLUE); g2.fillOval((int) (this.ROIPoint.getX() - (RADIUS >> 1) + 0.5), (int) (this.ROIPoint.getY() - (RADIUS >> 1) + 0.5), RADIUS, RADIUS); g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); this.updateROIInformationBox(g2); } this.solveConflict(); if (this.investPoint != null) { this.drawInformationBox(g2, this.investmentFlowChartJDialog.getInvestActivities(this.investPointIndex), investRect, investParams, investValues, GUIBundle.getString("InvestmentFlowLayerUI_Total_Invest"), totalInvestValue, COLOR_RED_BACKGROUND, COLOR_RED_BORDER); } if (this.ROIPoint != null) { this.drawInformationBox(g2, this.investmentFlowChartJDialog.getROIActivities(this.ROIPointIndex), ROIRect, ROIParams, ROIValues, GUIBundle.getString("InvestmentFlowLayerUI_Total_Return"), totalROIValue, COLOR_BLUE_BACKGROUND, COLOR_BLUE_BORDER); } this.drawTitle(g2); }
From source file:freemind.controller.Controller.java
public Object setEdgesRenderingHint(Graphics2D g) { Object renderingHint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, (getAntialiasEdges()) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); return renderingHint; }
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 .j av a 2s . c om g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15); g2.setColor(background_color); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect(x, y, width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); final Date date = activities.getDate().getTime(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy"); final String dateString = simpleDateFormat.format(date); final int padding = 5; int yy = y + padding + dateFontMetrics.getAscent(); g2.setFont(dateFont); g2.setColor(COLOR_BLUE); g2.drawString(dateString, ((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x, yy); int index = 0; final int dateInfoHeightMargin = 5; final int infoTotalHeightMargin = 5; final int paramValueHeightMargin = 0; yy += dateFontMetrics.getDescent() + dateInfoHeightMargin + Math.max(paramFontMetrics.getAscent(), valueFontMetrics.getAscent()); for (String param : params) { final String value = values.get(index++); g2.setColor(Color.BLACK); g2.setFont(paramFont); g2.drawString(param + ":", padding + x, yy); g2.setFont(valueFont); g2.drawString(value, width - padding - valueFontMetrics.stringWidth(value) + x, yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()); } if (values.size() > 1) { yy -= paramValueHeightMargin; yy += infoTotalHeightMargin; if (totalValue > 0.0) { g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR); } else if (totalValue < 0.0) { g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR); } g2.setFont(paramFont); g2.drawString(totalParam + ":", padding + x, yy); g2.setFont(valueFont); final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); final String totalValueStr = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalValue); g2.drawString(totalValueStr, width - padding - valueFontMetrics.stringWidth(totalValueStr) + x, yy); } g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:com.projity.contrib.calendar.JXXMonthView.java
/** * {@inheritDoc}/* w w w . j a va 2 s .c om*/ */ protected void paintComponent(Graphics g) { Object oldAAValue = null; Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D) g : null; if (g2 != null && _antiAlias) { oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } Rectangle clip = g.getClipBounds(); updateIfNecessary(); if (isOpaque()) { g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); } g.setColor(getForeground()); Color shadowColor = g.getColor(); shadowColor = new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int) (.20 * 255)); FontMetrics fm = g.getFontMetrics(); // Reset the calendar. _cal.setTimeInMillis(_firstDisplayedDate); // Center the calendars vertically in the available space. int y = _startY; for (int row = 0; row < _numCalRows; row++) { // Center the calendars horizontally in the available space. int x = _startX; int tmpX, tmpY; // Check if this row falls in the clip region. _bounds.x = 0; _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING); _bounds.width = getWidth(); _bounds.height = _calendarHeight; if (!_bounds.intersects(clip)) { _cal.add(Calendar.MONTH, _numCalCols); y += _calendarHeight + CALENDAR_SPACING; continue; } for (int column = 0; column < _numCalCols; column++) { String monthName = _monthsOfTheYear[_cal.get(Calendar.MONTH)]; monthName = monthName + " " + _cal.get(Calendar.YEAR); _bounds.x = _ltr ? x : x - _calendarWidth; _bounds.y = y + _boxPaddingY; _bounds.width = _calendarWidth; _bounds.height = _boxHeight; if (_bounds.intersects(clip)) { // Paint month name background. paintMonthStringBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); // Paint month name. g.setColor(getForeground()); tmpX = _ltr ? x + (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) : x - (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) - 1; tmpY = y + _boxPaddingY + _boxHeight - fm.getDescent(); g.drawString(monthName, tmpX, tmpY); if ((_dropShadowMask & MONTH_DROP_SHADOW) != 0) { g.setColor(shadowColor); g.drawString(monthName, tmpX + 1, tmpY + 1); g.setColor(getForeground()); } } _bounds.x = _ltr ? x : x - _calendarWidth; _bounds.y = y + _boxPaddingY + _boxHeight + _boxPaddingY + _boxPaddingY; _bounds.width = _calendarWidth; _bounds.height = _boxHeight; if (_bounds.intersects(clip)) { _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); Calendar weekCal = (Calendar) _cal.clone(); // Paint short representation of day of the week. int dayIndex = _firstDayOfWeek - 1; int month = weekCal.get(Calendar.MONTH); // dayIndex = (_cal.get(Calendar.DAY_OF_WEEK) -1) %7; for (int i = 0; i < DAYS_IN_WEEK; i++) { // PROJITY_MODIFICATION // set the week calendar to the current day of week and make sure it's still in this month weekCal.set(Calendar.DAY_OF_WEEK, dayIndex + 1); if (weekCal.get(Calendar.MONTH) != month) weekCal.roll(Calendar.DAY_OF_YEAR, 7); // make sure in this month tmpX = _ltr ? x + (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) + _boxPaddingX + (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2) : x - (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) - _boxPaddingX - (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2); tmpY = y + _boxPaddingY + _boxHeight + _boxPaddingY + _boxPaddingY + fm.getAscent(); boolean flagged = _flaggedWeekDates[dayIndex]; boolean colored = _coloredWeekDates[dayIndex]; calculateBoundsForDay(_bounds, weekCal, true); drawDay(colored, flagged, false, g, _daysOfTheWeek[dayIndex], tmpX, tmpY); // if ((_dropShadowMask & WEEK_DROP_SHADOW) != 0) { // calculateBoundsForDay(_bounds,weekCal,true); // add shadow arg // drawDay(colored,flagged,false,g,_daysOfTheWeek[dayIndex], tmpX + 1, // tmpY + 1); // } if (_selectedWeekDays[dayIndex]) { paintSelectedDayBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); } dayIndex++; if (dayIndex == 7) { dayIndex = 0; } } int lineOffset = 2; // Paint a line across bottom of days of the week. g.drawLine(_ltr ? x + 2 : x - 3, lineOffset + y + (_boxPaddingY * 3) + (_boxHeight * 2), _ltr ? x + _calendarWidth - 3 : x - _calendarWidth + 2, lineOffset + y + (_boxPaddingY * 3) + (_boxHeight * 2)); if ((_dropShadowMask & MONTH_LINE_DROP_SHADOW) != 0) { g.setColor(shadowColor); g.drawLine(_ltr ? x + 3 : x - 2, y + (_boxPaddingY * 3) + (_boxHeight * 2) + 1, _ltr ? x + _calendarWidth - 2 : x - _calendarWidth + 3, y + (_boxPaddingY * 3) + (_boxHeight * 2) + 1); g.setColor(getForeground()); } } // Check if the month to paint falls in the clip. _bounds.x = _startX + (_ltr ? column * (_calendarWidth + CALENDAR_SPACING) : -(column * (_calendarWidth + CALENDAR_SPACING) + _calendarWidth)); _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING); _bounds.width = _calendarWidth; _bounds.height = _calendarHeight; // Paint the month if it intersects the clip. If we don't move // the calendar forward a month as it would have if paintMonth // was called. if (_bounds.intersects(clip)) { paintMonth(g, column, row); } else { _cal.add(Calendar.MONTH, 1); } x += _ltr ? _calendarWidth + CALENDAR_SPACING : -(_calendarWidth + CALENDAR_SPACING); } y += _calendarHeight + CALENDAR_SPACING; } // Restore the calendar. _cal.setTimeInMillis(_firstDisplayedDate); if (g2 != null && _antiAlias) { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue); } }
From source file:anl.verdi.plot.jfree.XYBlockRenderer.java
/** * Draws the block representing the specified item. * * @param g2 the graphics device. * @param state the state.//from www . j ava2 s . c o m * @param dataArea the data area. * @param info the plot rendering info. * @param plot the plot. * @param domainAxis the x-axis. * @param rangeAxis the y-axis. * @param dataset the dataset. * @param series the series index. * @param item the item index. * @param crosshairState the crosshair state. * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double z = 0.0; double max = paintScale.getUpperBound(); double min = paintScale.getLowerBound(); if (dataset instanceof XYZDataset) z = ((XYZDataset) dataset).getZValue(series, item); //NOTE: so to get the max/min color instead of unknown (Qun He, UNC, 03/19/2009) if (z > max) z = max; if (z < min) z = min; Color p = (Color) this.paintScale.getPaint(z); double xx0 = domainAxis.valueToJava2D(x + this.xOffset, dataArea, plot.getDomainAxisEdge()); double yy0 = rangeAxis.valueToJava2D(y + this.yOffset, dataArea, plot.getRangeAxisEdge()); double xx1 = domainAxis.valueToJava2D(x + this.blockWidth + this.xOffset, dataArea, plot.getDomainAxisEdge()); double yy1 = rangeAxis.valueToJava2D(y + this.blockHeight + this.yOffset, dataArea, plot.getRangeAxisEdge()); Rectangle2D block; PlotOrientation orientation = plot.getOrientation(); if (orientation.equals(PlotOrientation.HORIZONTAL)) { block = new Rectangle2D.Double(Math.min(yy0, yy1), Math.min(xx0, xx1), Math.abs(yy1 - yy0), Math.abs(xx0 - xx1)); } else { block = new Rectangle2D.Double(Math.min(xx0, xx1), Math.min(yy0, yy1), Math.abs(xx1 - xx0), Math.abs(yy1 - yy0)); } g2.setColor(p); g2.fill(block); if (gridLinesEnabled) { boolean aaOn = false; if (g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING) == RenderingHints.VALUE_ANTIALIAS_ON) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); aaOn = true; } g2.setPaint(gridLineColor); g2.setStroke(gridLineStroke); g2.draw(block); if (aaOn) g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setStroke(basicStroke); g2.draw(block); } }
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 www . j a v a 2 s . c om g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15); g2.setColor(COLOR_BACKGROUND); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect(x, y, width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); //g2.drawImage(image, x + padding, y + ((height - imgHeight) >> 1), layer.getView()); g2.setFont(font); g2.setColor(COLOR_BLUE); int yy = y + ((height - fontMetrics.getHeight()) >> 1) + fontMetrics.getAscent(); g2.setFont(font); g2.setColor(COLOR_BLUE); g2.drawString(message, x + padding + imgWidth + imgMessageWidthMargin, yy); g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:org.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 . jav a 2s . c om } 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:org.tinymediamanager.TinyMediaManager.java
/** * The main method.// w w w. java 2 s . c om * * @param args * the arguments */ public static void main(String[] args) { // simple parse command line if (args != null && args.length > 0) { LOGGER.debug("TMM started with: " + Arrays.toString(args)); TinyMediaManagerCMD.parseParams(args); System.setProperty("java.awt.headless", "true"); } else { // no cmd params found, but if we are headless - display syntax String head = System.getProperty("java.awt.headless"); if (head != null && head.equals("true")) { LOGGER.info("TMM started 'headless', and without params -> displaying syntax "); TinyMediaManagerCMD.printSyntax(); System.exit(0); } } // check if we have write permissions to this folder try { RandomAccessFile f = new RandomAccessFile("access.test", "rw"); f.close(); Files.deleteIfExists(Paths.get("access.test")); } catch (Exception e2) { String msg = "Cannot write to TMM directory, have no rights - exiting."; if (!GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, msg); } else { System.out.println(msg); } System.exit(1); } // HACK for Java 7 and JavaFX not being in boot classpath // In Java 8 and on, this is installed inside jre/lib/ext // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8003171 and references // so we check if it is already existent in "new" directory, and if not, load it via reflection ;o) String dir = new File(LaunchUtil.getJVMPath()).getParentFile().getParent(); // bin, one deeper File jfx = new File(dir, "lib/ext/jfxrt.jar"); if (!jfx.exists()) { // java 7 jfx = new File(dir, "lib/jfxrt.jar"); if (jfx.exists()) { try { TmmOsUtils.addPath(jfx.getAbsolutePath()); } catch (Exception e) { LOGGER.debug("failed to load JavaFX - using old styles..."); } } } if (Globals.isDebug()) { ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader) cl).getURLs(); LOGGER.info("=== DEBUG CLASS LOADING ============================="); for (URL url : urls) { LOGGER.info(url.getFile()); } } LOGGER.info("====================================================="); LOGGER.info("=== tinyMediaManager (c) 2012-2016 Manuel Laggner ==="); LOGGER.info("====================================================="); LOGGER.info("tmm.version : " + ReleaseInfo.getRealVersion()); if (Globals.isDonator()) { LOGGER.info("tmm.supporter : THANKS FOR DONATING - ALL FEATURES UNLOCKED :)"); } LOGGER.info("os.name : " + System.getProperty("os.name")); LOGGER.info("os.version : " + System.getProperty("os.version")); LOGGER.info("os.arch : " + System.getProperty("os.arch")); LOGGER.trace("network.id : " + License.getMac()); LOGGER.info("java.version : " + System.getProperty("java.version")); if (Globals.isRunningJavaWebStart()) { LOGGER.info("java.webstart : true"); } if (Globals.isRunningWebSwing()) { LOGGER.info("java.webswing : true"); } // START character encoding debug debugCharacterEncoding("default encoding : "); System.setProperty("file.encoding", "UTF-8"); System.setProperty("sun.jnu.encoding", "UTF-8"); Field charset; try { // we cannot (re)set the properties while running inside JVM // so we trick it to reread it by setting them to null ;) charset = Charset.class.getDeclaredField("defaultCharset"); charset.setAccessible(true); charset.set(null, null); } catch (Exception e) { LOGGER.warn("Error resetting to UTF-8", e); } debugCharacterEncoding("set encoding to : "); // END character encoding debug // set GUI default language Locale.setDefault(Utils.getLocaleFromLanguage(Globals.settings.getLanguage())); LOGGER.info("System language : " + System.getProperty("user.language") + "_" + System.getProperty("user.country")); LOGGER.info( "GUI language : " + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry()); LOGGER.info("Scraper language : " + MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage()); LOGGER.info("TV Scraper lang : " + TvShowModuleManager.SETTINGS.getScraperLanguage()); // start EDT EventQueue.invokeLater(new Runnable() { public void run() { boolean newVersion = !Globals.settings.isCurrentVersion(); // same snapshots/svn considered as "new", for upgrades try { Thread.setDefaultUncaughtExceptionHandler(new Log4jBackstop()); if (!GraphicsEnvironment.isHeadless()) { Thread.currentThread().setName("main"); } else { Thread.currentThread().setName("headless"); LOGGER.debug("starting without GUI..."); } Toolkit tk = Toolkit.getDefaultToolkit(); tk.addAWTEventListener(TmmWindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK); if (!GraphicsEnvironment.isHeadless()) { setLookAndFeel(); } doStartupTasks(); // suppress logging messages from betterbeansbinding org.jdesktop.beansbinding.util.logging.Logger.getLogger(ELProperty.class.getName()) .setLevel(Level.SEVERE); // init ui logger TmmUILogCollector.init(); LOGGER.info("====================================================="); // init splash SplashScreen splash = null; if (!GraphicsEnvironment.isHeadless()) { splash = SplashScreen.getSplashScreen(); } Graphics2D g2 = null; if (splash != null) { g2 = splash.createGraphics(); if (g2 != null) { Font font = new Font("Dialog", Font.PLAIN, 14); g2.setFont(font); } else { LOGGER.debug("got no graphics from splash"); } } else { LOGGER.debug("no splash found"); } if (g2 != null) { updateProgress(g2, "starting tinyMediaManager", 0); splash.update(); } LOGGER.info("starting tinyMediaManager"); // upgrade check String oldVersion = Globals.settings.getVersion(); if (newVersion) { if (g2 != null) { updateProgress(g2, "upgrading to new version", 10); splash.update(); } UpgradeTasks.performUpgradeTasksBeforeDatabaseLoading(oldVersion); // do the upgrade tasks for the old version Globals.settings.setCurrentVersion(); Globals.settings.saveSettings(); } // proxy settings if (Globals.settings.useProxy()) { LOGGER.info("setting proxy"); Globals.settings.setProxy(); } // MediaInfo ///////////////////////////////////////////////////// if (g2 != null) { updateProgress(g2, "loading MediaInfo libs", 20); splash.update(); } MediaInfoUtils.loadMediaInfo(); // load modules ////////////////////////////////////////////////// if (g2 != null) { updateProgress(g2, "loading movie module", 30); splash.update(); } TmmModuleManager.getInstance().startUp(); TmmModuleManager.getInstance().registerModule(MovieModuleManager.getInstance()); TmmModuleManager.getInstance().enableModule(MovieModuleManager.getInstance()); if (g2 != null) { updateProgress(g2, "loading TV show module", 40); splash.update(); } TmmModuleManager.getInstance().registerModule(TvShowModuleManager.getInstance()); TmmModuleManager.getInstance().enableModule(TvShowModuleManager.getInstance()); if (g2 != null) { updateProgress(g2, "loading plugins", 50); splash.update(); } // just instantiate static - will block (takes a few secs) PluginManager.getInstance(); if (ReleaseInfo.isSvnBuild()) { PluginManager.loadClasspathPlugins(); } // do upgrade tasks after database loading if (newVersion) { if (g2 != null) { updateProgress(g2, "upgrading database to new version", 70); splash.update(); } UpgradeTasks.performUpgradeTasksAfterDatabaseLoading(oldVersion); } // launch application //////////////////////////////////////////// if (g2 != null) { updateProgress(g2, "loading ui", 80); splash.update(); } if (!GraphicsEnvironment.isHeadless()) { MainWindow window = new MainWindow("tinyMediaManager / " + ReleaseInfo.getRealVersion()); // finished //////////////////////////////////////////////////// if (g2 != null) { updateProgress(g2, "finished starting :)", 100); splash.update(); } // write a random number to file, to identify this instance (for // updater, tracking, whatsoever) Utils.trackEvent("startup"); TmmWindowSaver.getInstance().loadSettings(window); window.setVisible(true); // wizard for new user if (Globals.settings.newConfig) { Globals.settings.writeDefaultSettings(); // now all plugins are resolved - write again defaults! TinyMediaManagerWizard wizard = new TinyMediaManagerWizard(); wizard.setVisible(true); } // show changelog if (newVersion && !ReleaseInfo.getVersion().equals(oldVersion)) { // special case nightly/svn: if same snapshot version, do not display changelog Utils.trackEvent("updated"); showChangelog(); } } else { TinyMediaManagerCMD.startCommandLineTasks(); // wait for other tmm threads (artwork download et all) while (TmmTaskManager.getInstance().poolRunning()) { Thread.sleep(2000); } LOGGER.info("bye bye"); // MainWindows.shutdown() try { // send shutdown signal TmmTaskManager.getInstance().shutdown(); // save unsaved settings Globals.settings.saveSettings(); // hard kill TmmTaskManager.getInstance().shutdownNow(); // close database connection TmmModuleManager.getInstance().shutDown(); } catch (Exception ex) { LOGGER.warn(ex.getMessage()); } System.exit(0); } } catch (IllegalStateException e) { LOGGER.error("IllegalStateException", e); if (!GraphicsEnvironment.isHeadless() && e.getMessage().contains("file is locked")) { // MessageDialog.showExceptionWindow(e); ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$ MessageDialog dialog = new MessageDialog(MainWindow.getActiveInstance(), bundle.getString("tmm.problemdetected")); //$NON-NLS-1$ dialog.setImage(IconManager.ERROR); dialog.setText(bundle.getString("tmm.nostart"));//$NON-NLS-1$ dialog.setDescription(bundle.getString("tmm.nostart.instancerunning"));//$NON-NLS-1$ dialog.setResizable(true); dialog.pack(); dialog.setLocationRelativeTo(MainWindow.getActiveInstance()); dialog.setVisible(true); } System.exit(1); } catch (Exception e) { LOGGER.error("Exception while start of tmm", e); if (!GraphicsEnvironment.isHeadless()) { MessageDialog.showExceptionWindow(e); } System.exit(1); } } /** * Update progress on splash screen. * * @param text * the text */ private void updateProgress(Graphics2D g2, String text, int progress) { Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); g2.setComposite(AlphaComposite.Clear); g2.fillRect(20, 200, 480, 305); g2.setPaintMode(); g2.setColor(new Color(51, 153, 255)); g2.fillRect(22, 272, 452 * progress / 100, 21); g2.setColor(Color.black); g2.drawString(text + "...", 23, 310); int l = g2.getFontMetrics().stringWidth(ReleaseInfo.getRealVersion()); // bound right g2.drawString(ReleaseInfo.getRealVersion(), 480 - l, 325); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue); LOGGER.debug("Startup (" + progress + "%) " + text); } /** * Sets the look and feel. * * @throws Exception * the exception */ private void setLookAndFeel() throws Exception { // get font settings String fontFamily = Globals.settings.getFontFamily(); try { // sanity check fontFamily = Font.decode(fontFamily).getFamily(); } catch (Exception e) { fontFamily = "Dialog"; } int fontSize = Globals.settings.getFontSize(); if (fontSize < 12) { fontSize = 12; } String fontString = fontFamily + " " + fontSize; // Get the native look and feel class name // String laf = UIManager.getSystemLookAndFeelClassName(); Properties props = new Properties(); props.setProperty("controlTextFont", fontString); props.setProperty("systemTextFont", fontString); props.setProperty("userTextFont", fontString); props.setProperty("menuTextFont", fontString); // props.setProperty("windowTitleFont", "Dialog bold 20"); fontSize = Math.round((float) (fontSize * 0.833)); fontString = fontFamily + " " + fontSize; props.setProperty("subTextFont", fontString); props.setProperty("backgroundColor", "237 237 237"); props.setProperty("menuBackgroundColor", "237 237 237"); props.setProperty("controlBackgroundColor", "237 237 237"); props.setProperty("menuColorLight", "237 237 237"); props.setProperty("menuColorDark", "237 237 237"); props.setProperty("toolbarColorLight", "237 237 237"); props.setProperty("toolbarColorDark", "237 237 237"); props.setProperty("tooltipBackgroundColor", "255 255 255"); props.put("windowDecoration", "system"); props.put("logoString", ""); // Get the look and feel class name com.jtattoo.plaf.luna.LunaLookAndFeel.setTheme(props); String laf = "com.jtattoo.plaf.luna.LunaLookAndFeel"; // Install the look and feel UIManager.setLookAndFeel(laf); } /** * Does some tasks at startup */ private void doStartupTasks() { // rename downloaded files UpgradeTasks.renameDownloadedFiles(); // extract templates, if GD has not already done Utils.extractTemplates(); // check if a .desktop file exists if (Platform.isLinux()) { File desktop = new File(TmmOsUtils.DESKTOP_FILE); if (!desktop.exists()) { TmmOsUtils.createDesktopFileForLinux(desktop); } } } private void showChangelog() { // read the changelog try { final String changelog = Utils.readFileToString(Paths.get("changelog.txt")); if (StringUtils.isNotBlank(changelog)) { EventQueue.invokeLater(new Runnable() { @Override public void run() { WhatsNewDialog dialog = new WhatsNewDialog(changelog); dialog.pack(); dialog.setLocationRelativeTo(MainWindow.getActiveInstance()); dialog.setModalityType(ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } }); } } catch (IOException e) { // no file found LOGGER.warn(e.getMessage()); } } }); }