List of usage examples for java.awt FontMetrics stringWidth
public int stringWidth(String str)
From source file:org.multibit.viewsystem.swing.view.panels.ShowPreferencesPanel.java
private JPanel createAppearancePanel(int stentWidth) { MultiBitTitledPanel appearancePanel = new MultiBitTitledPanel( controller.getLocaliser().getString("showPreferencesPanel.appearanceTitle"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0;//w w w .java2 s.c o m constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; JPanel indent = MultiBitTitledPanel.getIndentPanel(1); appearancePanel.add(indent, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 4; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; JPanel stent = MultiBitTitledPanel.createStent(stentWidth); appearancePanel.add(stent, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 2; constraints.gridy = 3; constraints.weightx = 0.05; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.CENTER; appearancePanel.add( MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS), constraints); MultiBitLabel fontNameLabel = new MultiBitLabel( controller.getLocaliser().getString("fontChooser.fontName")); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 4; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; appearancePanel.add(fontNameLabel, constraints); fontNameTextLabel = new MultiBitLabel(""); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 4; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; appearancePanel.add(fontNameTextLabel, constraints); MultiBitLabel fontStyleLabel = new MultiBitLabel( controller.getLocaliser().getString("fontChooser.fontStyle")); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 5; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; appearancePanel.add(fontStyleLabel, constraints); fontStyleTextLabel = new MultiBitLabel(""); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 5; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; appearancePanel.add(fontStyleTextLabel, constraints); MultiBitLabel fontSizeLabel = new MultiBitLabel( controller.getLocaliser().getString("fontChooser.fontSize")); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 6; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; appearancePanel.add(fontSizeLabel, constraints); fontSizeTextLabel = new MultiBitLabel(""); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 6; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; appearancePanel.add(fontSizeTextLabel, constraints); ChooseFontAction chooseFontAction = new ChooseFontAction(controller, this, null); MultiBitButton fontChooserButton = new MultiBitButton(chooseFontAction, controller); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 7; constraints.weightx = 1; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; appearancePanel.add(fontChooserButton, constraints); constraints.fill = GridBagConstraints.VERTICAL; constraints.gridx = 4; constraints.gridy = 8; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; appearancePanel.add(MultiBitTitledPanel.createStent(1, 30), constraints); MultiBitLabel lookAndFeelLabel = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.lookAndFeel")); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 9; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; appearancePanel.add(lookAndFeelLabel, constraints); originalLookAndFeel = controller.getModel().getUserPreference(CoreModel.LOOK_AND_FEEL); LookAndFeelInfo[] lookAndFeels = UIManager.getInstalledLookAndFeels(); lookAndFeelComboBox = new JComboBox(); lookAndFeelComboBox.addItem(localisedSystemLookAndFeelName); if (lookAndFeels != null) { for (LookAndFeelInfo info : lookAndFeels) { lookAndFeelComboBox.addItem(info.getName()); if (info.getName().equalsIgnoreCase(originalLookAndFeel)) { lookAndFeelComboBox.setSelectedItem(info.getName()); } } } if (originalLookAndFeel == null || originalLookAndFeel.equals("") || CoreModel.SYSTEM_LOOK_AND_FEEL.equalsIgnoreCase(originalLookAndFeel)) { lookAndFeelComboBox.setSelectedItem(localisedSystemLookAndFeelName); } lookAndFeelComboBox.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); lookAndFeelComboBox.setOpaque(false); FontMetrics fontMetrics = getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()); int textWidth = Math.max(fontMetrics.stringWidth("CDE/Motif"), fontMetrics.stringWidth("Windows classic")); Dimension preferredSize = new Dimension(textWidth + TICKER_COMBO_WIDTH_DELTA, fontMetrics.getHeight() + EXCHANGE_COMBO_HEIGHT_DELTA); lookAndFeelComboBox.setPreferredSize(preferredSize); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 9; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; appearancePanel.add(lookAndFeelComboBox, constraints); JPanel fill1 = new JPanel(); fill1.setOpaque(false); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 4; constraints.gridy = 10; constraints.weightx = 20; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; appearancePanel.add(fill1, constraints); return appearancePanel; }
From source file:ded.ui.DiagramController.java
/** The core of the paint routine, after we decide whether to interpose * another buffer. *//* ww w .ja va 2s. c o m*/ private void innerPaint(Graphics g) { super.paint(g); // I do not know the proper way to get a font set automatically // in a Graphics object. Calling JComponent.setFont has gotten // me nowhere. Setting it myself when I first get control // seems to work; but note that I have to do this *after* // calling super.paint(). g.setFont(this.dedWindow.diagramFont); // Filename label. if (this.diagram.drawFileName && !this.fileName.isEmpty()) { String name = new File(this.fileName).getName(); FontMetrics fm = g.getFontMetrics(); LineMetrics lm = fm.getLineMetrics(name, g); int x = fileNameLabelMargin; int y = fileNameLabelMargin + (int) lm.getAscent(); g.drawString(name, x, y); y += (int) lm.getUnderlineOffset() + 1 /*...*/; g.drawLine(x, y, x + fm.stringWidth(name), y); } // Controllers. for (Controller c : this.controllers) { if (c.isSelected()) { c.paintSelectionBackground(g); } c.paint(g); } // Lasso rectangle. if (this.mode == Mode.DCM_RECT_LASSO) { Rectangle r = this.getLassoRect(); g.drawRect(r.x, r.y, r.width, r.height); } // Current focused Component. if (debugFocus) { KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); Component fo = kfm.getFocusOwner(); g.drawString("Focus: " + fo, 3, this.getHeight() - 22); } // Mode label. if (this.mode != Mode.DCM_SELECT) { g.drawString("Mode: " + this.mode.description, 3, this.getHeight() - 4); } else if (this.fpsMeasurementMode) { this.fpsFrameCount++; long current = System.currentTimeMillis(); long millis = current - this.fpsStartMillis; if (millis > 1000) { // Update the FPS measurement with the results for this // interval. this.fpsSampleCount++; this.fpsMeasurement = "FPS: " + this.fpsFrameCount + " (millis=" + millis + ", samples=" + this.fpsSampleCount + ")"; // Reset the counters. this.fpsStartMillis = current; this.fpsFrameCount = 0; } g.drawString(this.fpsMeasurement + " (Ctrl+G to stop)", 3, this.getHeight() - 4); } }
From source file:spectrogram.Spectrogram.java
/** * Define the size and position of different parts of image and add global labels *//*from w w w .j a v a 2 s . co m*/ private void initImage() { colorModel = IndexColorTables.getColorTable(color); // use anti-aliasing font representation System.setProperty("awt.useSystemAAFontSettings", "on"); System.setProperty("swing.aatext", "true"); // img contains the output image with all the labels img = new BufferedImage(outX, outY, BufferedImage.TYPE_BYTE_INDEXED, colorModel); grph = img.createGraphics(); grph.setBackground(Color.white); grph.clearRect(0, 0, outX, outY); String fontName = getAGoodFont(); lblFont = new Font(fontName, Font.PLAIN, 16); titleFont = new Font(fontName, Font.BOLD, 18); FontMetrics titleMetrics = grph.getFontMetrics(titleFont); labelMetrics = grph.getFontMetrics(lblFont); em = labelMetrics.stringWidth("M"); String title; String utcDate; String hrTime = TimeAndDate.hrTime(duration); String cname; if (useAltData) { cname = "Test Data"; if (testDataFilename != null && !testDataFilename.isEmpty()) { File f = new File(testDataFilename); cname = f.getName(); } if (rawDataFilename != null && !rawDataFilename.isEmpty()) { File f = new File(rawDataFilename); cname = f.getName(); } if (channelName != null && !channelName.isEmpty()) { cname = channelName; } if (startGPS == 0) { Date now = new Date(); startGPS = (int) TimeAndDate.utc2gps(now.getTime() / 1000); } } else { cname = channelName; } utcDate = TimeAndDate.gpsAsUtcString(startGPS); title = String.format("%1$s %2$s - %3$,d (%4$s)", cname, utcDate, startGPS, hrTime); titleHeight = titleMetrics.getHeight(); int titleWidth = titleMetrics.stringWidth(title); lblHeight = labelMetrics.getHeight(); int lblWidth = labelMetrics.stringWidth("99,999"); int tbMargin = 10; int lrMargin = 10; // plot title int tx = outX / 2 - titleWidth / 2; int ty = (int) Math.round(lblHeight * 1.5); grph.setPaint(Color.BLACK); grph.setFont(titleFont); grph.drawString(title, tx, ty); // calc and draw color map int cmWidth = 48; int cmLblWidth = labelMetrics.stringWidth("0.000000") + em; int cmLeft = outX - lrMargin * 2 - titleHeight - cmLblWidth - cmWidth; imgY0 = titleHeight + tbMargin * 2; dimY = outY - imgY0 - lblHeight * 5 - tbMargin; cmRect = new Rectangle(cmLeft, imgY0, cmWidth, dimY); grph.drawRect(cmLeft, imgY0, cmWidth, dimY); // calc and draw image rectangle imgX0 = lrMargin * 2 + titleHeight + lblWidth; dimX = cmLeft - imgX0 - lrMargin; pltRect = new Rectangle(imgX0, imgY0, dimX, dimY); grph.drawRect(imgX0, imgY0, dimX, dimY); // y-axis label String leftAxisLabel = "Frequency (Hz)"; grph.setColor(Color.BLACK); tx = lblHeight + lrMargin; titleWidth = titleMetrics.stringWidth(leftAxisLabel); ty = outY / 2 + titleWidth / 2; drawRotatedText(tx, ty, -90, leftAxisLabel); // color map label String rightAxisLabel = scaling.toString(); if (norm) { rightAxisLabel += " Normalized."; } tx = outX - lblHeight - lrMargin; titleWidth = titleMetrics.stringWidth(rightAxisLabel); ty = outY / 2 + titleWidth / 2; drawRotatedText(tx, ty, -90, rightAxisLabel); int nsamples = (int) (duration * sampleRate); colPerSample = 1; if (nsamples < dimX) { // we have more pixels available than we have samples so making it pretty takes some work colPerSample = dimX / nsamples; dimX = colPerSample * nsamples; } rast = img.getRaster(); fillColorMap(); }
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 v a2s . co m*/ 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.multibit.viewsystem.swing.view.panels.ShowPreferencesPanel.java
private JPanel createTickerPanel(int stentWidth) { // Load up the original values. originalShowTicker = !Boolean.FALSE.toString() .equals(controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW)); originalExchange1 = controller.getModel().getUserPreference(ExchangeModel.TICKER_FIRST_ROW_EXCHANGE); originalCurrency1 = controller.getModel().getUserPreference(ExchangeModel.TICKER_FIRST_ROW_CURRENCY); // Map MtGox to Bitstamp + USD if (ExchangeData.MT_GOX_EXCHANGE_NAME.equalsIgnoreCase(originalExchange1)) { originalExchange1 = ExchangeData.BITSTAMP_EXCHANGE_NAME; controller.getModel().setUserPreference(ExchangeModel.TICKER_FIRST_ROW_EXCHANGE, ExchangeData.BITSTAMP_EXCHANGE_NAME); originalCurrency1 = "USD"; controller.getModel().setUserPreference(ExchangeModel.TICKER_FIRST_ROW_CURRENCY, "USD"); }//from w w w. j a va 2 s . com originalShowSecondRow = Boolean.TRUE.toString() .equals(controller.getModel().getUserPreference(ExchangeModel.TICKER_SHOW_SECOND_ROW)); originalExchange2 = controller.getModel().getUserPreference(ExchangeModel.TICKER_SECOND_ROW_EXCHANGE); originalCurrency2 = controller.getModel().getUserPreference(ExchangeModel.TICKER_SECOND_ROW_CURRENCY); // Map MtGox to Bitstamp if (ExchangeData.MT_GOX_EXCHANGE_NAME.equalsIgnoreCase(originalExchange2)) { originalExchange2 = ExchangeData.BITSTAMP_EXCHANGE_NAME; controller.getModel().setUserPreference(ExchangeModel.TICKER_SECOND_ROW_EXCHANGE, ExchangeData.BITSTAMP_EXCHANGE_NAME); originalCurrency2 = "USD"; controller.getModel().setUserPreference(ExchangeModel.TICKER_SECOND_ROW_CURRENCY, "USD"); } MultiBitTitledPanel tickerPanel = new MultiBitTitledPanel( controller.getLocaliser().getString("showPreferencesPanel.ticker.title2"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 3; constraints.gridy = 3; constraints.weightx = 0.05; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.CENTER; tickerPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS), constraints); String showTickerText = controller.getLocaliser().getString("multiBitFrame.ticker.show.text"); if (showTickerText != null && showTickerText.length() >= 1) { // Capitalise text (this is to save adding a new I18n term. showTickerText = Character.toUpperCase(showTickerText.charAt(0)) + showTickerText.toLowerCase().substring(1); } showTicker = new JCheckBox(showTickerText); showTicker.setOpaque(false); showTicker.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showTicker.setSelected(originalShowTicker); exchangeInformationLabel = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.ticker.exchangeInformation")); exchangeInformationLabel.setVisible(originalShowBitcoinConvertedToFiat); showBitcoinConvertedToFiat = new JCheckBox( controller.getLocaliser().getString("showPreferencesPanel.ticker.showBitcoinConvertedToFiat")); showBitcoinConvertedToFiat.setOpaque(false); showBitcoinConvertedToFiat.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showBitcoinConvertedToFiat.setSelected(originalShowBitcoinConvertedToFiat); showBitcoinConvertedToFiat.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean selectedChange = (e.getStateChange() == ItemEvent.SELECTED); boolean unSelectedChange = (e.getStateChange() == ItemEvent.DESELECTED); if (exchangeInformationLabel != null) { if (selectedChange) { exchangeInformationLabel.setVisible(true); } if (unSelectedChange) { exchangeInformationLabel.setVisible(false); } } } }); showExchange = new JCheckBox(controller.getLocaliser().getString("tickerTableModel.exchange")); showExchange.setOpaque(false); showExchange.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showCurrency = new JCheckBox(controller.getLocaliser().getString("tickerTableModel.currency")); showCurrency.setOpaque(false); showCurrency.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showLastPrice = new JCheckBox(controller.getLocaliser().getString("tickerTableModel.lastPrice")); showLastPrice.setOpaque(false); showLastPrice.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showBid = new JCheckBox(controller.getLocaliser().getString("tickerTableModel.bid")); showBid.setOpaque(false); showBid.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showAsk = new JCheckBox(controller.getLocaliser().getString("tickerTableModel.ask")); showAsk.setOpaque(false); showAsk.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); String tickerColumnsToShow = controller.getModel().getUserPreference(ExchangeModel.TICKER_COLUMNS_TO_SHOW); if (tickerColumnsToShow == null || tickerColumnsToShow.equals("")) { tickerColumnsToShow = TickerTableModel.DEFAULT_COLUMNS_TO_SHOW; } originalShowCurrency = tickerColumnsToShow.contains(TickerTableModel.TICKER_COLUMN_CURRENCY); showCurrency.setSelected(originalShowCurrency); originalShowRate = tickerColumnsToShow.contains(TickerTableModel.TICKER_COLUMN_LAST_PRICE); showLastPrice.setSelected(originalShowRate); originalShowBid = tickerColumnsToShow.contains(TickerTableModel.TICKER_COLUMN_BID); showBid.setSelected(originalShowBid); originalShowAsk = tickerColumnsToShow.contains(TickerTableModel.TICKER_COLUMN_ASK); showAsk.setSelected(originalShowAsk); originalShowExchange = tickerColumnsToShow.contains(TickerTableModel.TICKER_COLUMN_EXCHANGE); showExchange.setSelected(originalShowExchange); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 4; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 4; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showTicker, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 5; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 4; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showBitcoinConvertedToFiat, constraints); constraints.fill = GridBagConstraints.VERTICAL; constraints.gridx = 0; constraints.gridy = 6; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(MultiBitTitledPanel.createStent(1, 12), constraints); MultiBitTitledPanel.addLeftJustifiedTextAtIndent( controller.getLocaliser().getString("showPreferencesPanel.ticker.columnsToShow"), 7, tickerPanel); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 8; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showExchange, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 9; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showCurrency, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 10; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showLastPrice, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 11; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showBid, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 12; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showAsk, constraints); constraints.fill = GridBagConstraints.VERTICAL; constraints.gridx = 1; constraints.gridy = 13; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(MultiBitTitledPanel.createStent(1, 13), constraints); MultiBitTitledPanel.addLeftJustifiedTextAtIndent( controller.getLocaliser().getString("showPreferencesPanel.ticker.firstRow"), 14, tickerPanel); MultiBitLabel exchangeLabel1 = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.ticker.exchange")); exchangeLabel1.setHorizontalAlignment(JLabel.TRAILING); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 15; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; tickerPanel.add(exchangeLabel1, constraints); String exchangeToUse1; if (originalExchange1 == null | "".equals(originalExchange1)) { exchangeToUse1 = ExchangeData.DEFAULT_EXCHANGE; } else { exchangeToUse1 = originalExchange1; } String exchangeToUse2; if (originalExchange2 == null | "".equals(originalExchange2)) { exchangeToUse2 = ExchangeData.DEFAULT_EXCHANGE; } else { exchangeToUse2 = originalExchange2; } exchangeComboBox1 = new JComboBox(ExchangeData.getAvailableExchanges()); exchangeComboBox1.setSelectedItem(exchangeToUse1); exchangeComboBox1.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); exchangeComboBox1.setOpaque(false); FontMetrics fontMetrics = getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()); int textWidth = Math.max(fontMetrics.stringWidth(ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME), fontMetrics.stringWidth("USD")) + COMBO_WIDTH_DELTA; Dimension preferredSize = new Dimension(textWidth + TICKER_COMBO_WIDTH_DELTA, fontMetrics.getHeight() + EXCHANGE_COMBO_HEIGHT_DELTA); exchangeComboBox1.setPreferredSize(preferredSize); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 15; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 2; constraints.anchor = GridBagConstraints.LINE_START; JPanel stent = MultiBitTitledPanel.createStent(stentWidth); tickerPanel.add(stent, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 15; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(exchangeComboBox1, constraints); oerMessageLabel1 = new MultiBitLabel( " " + controller.getLocaliser().getString("showPreferencesPanel.getAppId.label")); oerMessageLabel1.setForeground(Color.GREEN.darker().darker()); boolean showMessageLabel1 = isBrowserSupported() && ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME.equalsIgnoreCase(exchangeToUse1) && (originalOERApiCode == null || originalOERApiCode.trim().length() == 0); oerMessageLabel1.setVisible(showMessageLabel1); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 5; constraints.gridy = 15; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(oerMessageLabel1, constraints); MultiBitLabel currencyLabel1 = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.ticker.currency")); currencyLabel1.setHorizontalAlignment(JLabel.TRAILING); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 16; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; tickerPanel.add(currencyLabel1, constraints); // Make sure the exchange1 has been created and initialised the list of // currencies. if (mainFrame != null && mainFrame.getTickerTimerTask1() != null) { TickerTimerTask tickerTimerTask = mainFrame.getTickerTimerTask1(); synchronized (tickerTimerTask) { if (tickerTimerTask.getExchange() == null) { tickerTimerTask.createExchangeObjects(exchangeToUse1); } } } currencyComboBox1 = new JComboBox(); Collection<String> currenciesToUse = ExchangeData.getAvailableCurrenciesForExchange(exchangeToUse1); if (currenciesToUse != null) { for (String currency : currenciesToUse) { String item = currency; String description = CurrencyConverter.INSTANCE.getCurrencyCodeToDescriptionMap().get(currency); if (description != null && description.trim().length() > 0) { item = item + " (" + description + ")"; } currencyComboBox1.addItem(item); if (currency.equals(originalCurrency1)) { currencyComboBox1.setSelectedItem(item); } } } currencyComboBox1.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); currencyComboBox1.setOpaque(false); currencyComboBox1.setPreferredSize(preferredSize); exchangeComboBox1.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if (event.getStateChange() == ItemEvent.SELECTED) { Object item = event.getItem(); String exchangeShortName = item.toString(); // Make sure the exchange1 has been created and initialised // the list of currencies. if (mainFrame != null && mainFrame.getTickerTimerTask1() != null) { TickerTimerTask tickerTimerTask = mainFrame.getTickerTimerTask1(); synchronized (tickerTimerTask) { tickerTimerTask.createExchangeObjects(exchangeShortName); currencyComboBox1.removeAllItems(); Collection<String> currenciesToUse = ExchangeData .getAvailableCurrenciesForExchange(exchangeShortName); if (currenciesToUse != null) { for (String currency : currenciesToUse) { String loopItem = currency; String description = CurrencyConverter.INSTANCE .getCurrencyCodeToDescriptionMap().get(currency); if (description != null && description.trim().length() > 0) { loopItem = loopItem + " (" + description + ")"; } currencyComboBox1.addItem(loopItem); } } } } // Enable the OpenExchangeRates App ID if required. boolean showOER = ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME .equalsIgnoreCase(exchangeShortName) || ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME .equalsIgnoreCase((String) exchangeComboBox2.getSelectedItem()); oerStent.setVisible(showOER); oerApiCodeLabel.setVisible(showOER); oerApiCodeTextField.setVisible(showOER); getOerAppIdButton.setVisible(showOER); boolean showMessageLabel = isBrowserSupported() && ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME.equalsIgnoreCase(exchangeShortName) && (oerApiCodeTextField.getText() == null || oerApiCodeTextField.getText().trim().length() == 0); oerMessageLabel1.setVisible(showMessageLabel); } } }); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 16; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(currencyComboBox1, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 17; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(MultiBitTitledPanel.createStent(12, 12), constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 18; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 2; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(MultiBitTitledPanel.createStent(fontMetrics.stringWidth(exchangeInformationLabel.getText()), fontMetrics.getHeight()), constraints); tickerPanel.add(exchangeInformationLabel, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 19; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(MultiBitTitledPanel.createStent(12, 12), constraints); MultiBitTitledPanel.addLeftJustifiedTextAtIndent( controller.getLocaliser().getString("showPreferencesPanel.ticker.secondRow"), 20, tickerPanel); showSecondRowCheckBox = new JCheckBox( controller.getLocaliser().getString("showPreferencesPanel.ticker.showSecondRow")); showSecondRowCheckBox.setOpaque(false); showSecondRowCheckBox.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); showSecondRowCheckBox.addItemListener(new ChangeTickerShowSecondRowListener()); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 21; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(showSecondRowCheckBox, constraints); exchangeLabel2 = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.ticker.exchange")); exchangeLabel2.setHorizontalAlignment(JLabel.TRAILING); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 22; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; tickerPanel.add(exchangeLabel2, constraints); exchangeComboBox2 = new JComboBox(ExchangeData.getAvailableExchanges()); exchangeComboBox2.setSelectedItem(exchangeToUse2); exchangeComboBox2.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); exchangeComboBox2.setOpaque(false); exchangeComboBox2.setPreferredSize(preferredSize); exchangeComboBox2.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if (event.getStateChange() == ItemEvent.SELECTED) { Object item = event.getItem(); String exchangeShortName = item.toString(); // Make sure the exchange2 has been created and initialised // the list of currencies. if (mainFrame != null && mainFrame.getTickerTimerTask2() != null) { TickerTimerTask tickerTimerTask = mainFrame.getTickerTimerTask2(); synchronized (tickerTimerTask) { tickerTimerTask.createExchangeObjects(exchangeShortName); currencyComboBox2.removeAllItems(); Collection<String> currenciesToUse = ExchangeData .getAvailableCurrenciesForExchange(exchangeShortName); if (currenciesToUse != null) { for (String currency : currenciesToUse) { String loopItem = currency; String description = CurrencyConverter.INSTANCE .getCurrencyCodeToDescriptionMap().get(currency); if (description != null && description.trim().length() > 0) { loopItem = loopItem + " (" + description + ")"; } currencyComboBox2.addItem(loopItem); } } } } // Enable the OpenExchangeRates App ID if required. boolean showOER = ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME .equalsIgnoreCase(exchangeShortName) || ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME .equalsIgnoreCase((String) exchangeComboBox1.getSelectedItem()); oerStent.setVisible(showOER); oerApiCodeLabel.setVisible(showOER); oerApiCodeTextField.setVisible(showOER); getOerAppIdButton.setVisible(showOER); boolean showMessageLabel = isBrowserSupported() && ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME.equalsIgnoreCase(exchangeShortName) && (oerApiCodeTextField.getText() == null || oerApiCodeTextField.getText().trim().length() == 0); oerMessageLabel2.setVisible(showMessageLabel); } } }); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 22; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(exchangeComboBox2, constraints); oerMessageLabel2 = new MultiBitLabel( " " + controller.getLocaliser().getString("showPreferencesPanel.getAppId.label")); oerMessageLabel2.setForeground(Color.GREEN.darker().darker()); boolean showMessageLabel2 = isBrowserSupported() && ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME.equalsIgnoreCase(exchangeToUse2) && (originalOERApiCode == null || originalOERApiCode.trim().length() == 0); oerMessageLabel2.setVisible(showMessageLabel2); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 5; constraints.gridy = 22; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(oerMessageLabel2, constraints); currencyLabel2 = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.ticker.currency")); currencyLabel2.setHorizontalAlignment(JLabel.TRAILING); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 23; constraints.weightx = 0.3; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; tickerPanel.add(currencyLabel2, constraints); // Make sure the exchange2 has been created and initialised the list of // currencies. if (mainFrame != null && mainFrame.getTickerTimerTask2() != null) { TickerTimerTask tickerTimerTask = mainFrame.getTickerTimerTask2(); synchronized (tickerTimerTask) { if (tickerTimerTask.getExchange() == null) { tickerTimerTask.createExchangeObjects(exchangeToUse2); } } } currencyComboBox2 = new JComboBox(); currenciesToUse = ExchangeData.getAvailableCurrenciesForExchange(exchangeToUse2); if (currenciesToUse != null) { for (String currency : currenciesToUse) { String loopItem = currency; String description = CurrencyConverter.INSTANCE.getCurrencyCodeToDescriptionMap().get(currency); if (description != null && description.trim().length() > 0) { loopItem = loopItem + " (" + description + ")"; } currencyComboBox2.addItem(loopItem); if (currency.equals(originalCurrency2)) { currencyComboBox2.setSelectedItem(loopItem); } } } currencyComboBox2.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); currencyComboBox2.setOpaque(false); currencyComboBox2.setPreferredSize(preferredSize); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 23; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(currencyComboBox2, constraints); showSecondRowCheckBox.setSelected(originalShowSecondRow); enableTickerSecondRow(originalShowSecondRow); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 24; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(MultiBitTitledPanel.createStent(12, 12), constraints); JPanel fill1 = new JPanel(); fill1.setOpaque(false); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 5; constraints.gridy = 25; constraints.weightx = 20; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; tickerPanel.add(fill1, constraints); boolean showOerSignup = ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME.equalsIgnoreCase(exchangeToUse1) || ExchangeData.OPEN_EXCHANGE_RATES_EXCHANGE_NAME.equalsIgnoreCase(exchangeToUse2); oerStent = MultiBitTitledPanel.createStent(12, 12); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 26; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; oerStent.setVisible(showOerSignup); tickerPanel.add(oerStent, constraints); oerApiCodeLabel = new MultiBitLabel( controller.getLocaliser().getString("showPreferencesPanel.oerLabel.text")); oerApiCodeLabel.setToolTipText(HelpContentsPanel .createTooltipText(controller.getLocaliser().getString("showPreferencesPanel.oerLabel.tooltip"))); oerApiCodeLabel.setVisible(showOerSignup); oerApiCodeTextField = new MultiBitTextField("", 25, controller); oerApiCodeTextField.setHorizontalAlignment(JLabel.LEADING); oerApiCodeTextField.setMinimumSize(new Dimension(API_CODE_FIELD_WIDTH, API_CODE_FIELD_HEIGHT)); oerApiCodeTextField.setPreferredSize(new Dimension(API_CODE_FIELD_WIDTH, API_CODE_FIELD_HEIGHT)); oerApiCodeTextField.setMaximumSize(new Dimension(API_CODE_FIELD_WIDTH, API_CODE_FIELD_HEIGHT)); oerApiCodeTextField.setVisible(showOerSignup); oerApiCodeTextField.setText(originalOERApiCode); oerApiCodeTextField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent arg0) { } @Override public void focusLost(FocusEvent arg0) { String apiCode = oerApiCodeTextField.getText(); if (apiCode != null && !(WhitespaceTrimmer.trim(apiCode).length() == 0) && !apiCode.equals( controller.getModel().getUserPreference(ExchangeModel.OPEN_EXCHANGE_RATES_API_CODE))) { // New API code. // Check its length if (!(apiCode.trim().length() == LENGTH_OF_OPEN_EXCHANGE_RATE_APP_ID) && !apiCode.equals(haveShownErrorMessageForApiCode)) { haveShownErrorMessageForApiCode = apiCode; // Give user a message that App ID is not in the correct format. JOptionPane.showMessageDialog(null, new String[] { controller .getLocaliser().getString("showPreferencesPanel.oerValidationError.text1"), " ", controller.getLocaliser() .getString("showPreferencesPanel.oerValidationError.text2"), controller.getLocaliser() .getString("showPreferencesPanel.oerValidationError.text3") }, controller.getLocaliser().getString( "showPreferencesPanel.oerValidationError.title"), JOptionPane.ERROR_MESSAGE, ImageLoader.createImageIcon(ImageLoader.EXCLAMATION_MARK_ICON_FILE)); return; } } updateApiCode(); } }); oerApiCodeTextField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String apiCode = oerApiCodeTextField.getText(); if (apiCode != null && !(WhitespaceTrimmer.trim(apiCode).length() == 0) && !apiCode.equals( controller.getModel().getUserPreference(ExchangeModel.OPEN_EXCHANGE_RATES_API_CODE))) { // New API code. // Check its length if (!(apiCode.trim().length() == LENGTH_OF_OPEN_EXCHANGE_RATE_APP_ID) && !apiCode.equals(haveShownErrorMessageForApiCode)) { haveShownErrorMessageForApiCode = apiCode; // Give user a message that App ID is not in the correct format. JOptionPane.showMessageDialog(null, new String[] { controller.getLocaliser() .getString("showPreferencesPanel.oerValidationError.text1"), controller.getLocaliser() .getString("showPreferencesPanel.oerValidationError.text2"), controller.getLocaliser() .getString("showPreferencesPanel.oerValidationError.text3") }, controller.getLocaliser().getString( "showPreferencesPanel.oerValidationError.title"), JOptionPane.ERROR_MESSAGE, ImageLoader.createImageIcon(ImageLoader.EXCLAMATION_MARK_ICON_FILE)); return; } } updateApiCode(); } }); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 27; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; tickerPanel.add(oerApiCodeLabel, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 27; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 2; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(oerApiCodeTextField, constraints); if (isBrowserSupported()) { getOerAppIdButton = new MultiBitButton( controller.getLocaliser().getString("showPreferencesPanel.getAppId.text")); getOerAppIdButton .setToolTipText(controller.getLocaliser().getString("showPreferencesPanel.getAppId.tooltip")); getOerAppIdButton.setVisible(showOerSignup); getOerAppIdButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { openURI(new URI(OPEN_EXCHANGE_RATES_SIGN_UP_URI)); } catch (URISyntaxException e) { log.debug(e.getMessage()); } } }); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 4; constraints.gridy = 28; constraints.weightx = 1; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; tickerPanel.add(getOerAppIdButton, constraints); } return tickerPanel; }
From source file:org.gumtree.vis.awt.JChartPanel.java
private void drawTextInputBox(Graphics2D g2) { if (textInputFlag && textInputPoint != null) { // g2.drawChars("Input Text Here".toCharArray(), 1, 60, (int) textInputPoint.getX(), (int) textInputPoint.getY()); Color oldColor = g2.getColor(); g2.setColor(Color.BLACK); String inputText = textInputContent == null ? "" : textInputContent; FontMetrics fm = g2.getFontMetrics(); // int sWidth; // if (textInputCursorIndex == 0 || inputText.length() == 0) { // sWidth = 0; // } else if (textInputCursorIndex < inputText.length()){ // sWidth = fm.stringWidth(inputText.substring(0, textInputCursorIndex)); // } else { // sWidth = fm.stringWidth(inputText); // } String[] lines = inputText.split("\n", 100); int cursorY = 0; int cursorX = 0; int charCount = 0; int maxWidth = 0; int maxHeight = 0; for (int i = 0; i < lines.length; i++) { g2.drawString(lines[i], (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3 + i * 15); // charCount += lines[i].length() + 1; if (textInputCursorIndex > charCount && textInputCursorIndex < charCount + lines[i].length() + 1) { cursorY = i;/*w w w . j av a 2 s . c o m*/ cursorX = fm.stringWidth(lines[i].substring(0, textInputCursorIndex - charCount)); } else if (textInputCursorIndex == charCount + lines[i].length() + 1) { cursorY = i + 1; cursorX = 0; } charCount += lines[i].length() + 1; int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } maxHeight = 15 * lines.length; // g2.drawString(inputText, (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3); g2.setColor(Color.MAGENTA); // g2.drawString("|", (float) textInputPoint.getX() + 2 + sWidth, (float) textInputPoint.getY() - 3); g2.drawLine((int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + (cursorY - 1) * 15, (int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + cursorY * 15); g2.setColor(Color.BLACK); g2.setColor(oldColor); // int boxWidth = fm.stringWidth(inputText) + 10; if (maxWidth < 100) { maxWidth = 100; } Rectangle2D inputBox = new Rectangle2D.Double(textInputPoint.getX(), textInputPoint.getY() - 15, maxWidth + 8, maxHeight); // ChartMaskingUtilities.drawMaskBoarder(g2, inputBox); Color fillColor = new Color(250, 250, 50, 30); g2.setPaint(fillColor); g2.fill(inputBox); g2.setColor(Color.ORANGE); g2.drawRect((int) textInputPoint.getX(), (int) textInputPoint.getY() - 15, maxWidth + 8, maxHeight); } if (textContentMap.size() > 0) { Color oldColor = g2.getColor(); g2.setColor(Color.BLACK); Rectangle2D imageArea = getScreenDataArea(); for (Entry<Rectangle2D, String> entry : textContentMap.entrySet()) { Rectangle2D rect = entry.getKey(); Point2D screenPoint = ChartMaskingUtilities .translateChartPoint(new Point2D.Double(rect.getX(), rect.getY()), imageArea, getChart()); String text = entry.getValue(); if (text == null) { continue; } String[] lines = text.split("\n"); g2.setColor(Color.BLACK); for (int i = 0; i < lines.length; i++) { g2.drawString(lines[i], (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3 + i * 15); } if (rect == selectedTextWrapper) { FontMetrics fm = g2.getFontMetrics(); int maxWidth = 0; int maxHeight = 0; for (int i = 0; i < lines.length; i++) { int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } maxHeight = 15 * lines.length; if (maxWidth < 100) { maxWidth = 100; } Rectangle2D inputBox = new Rectangle2D.Double(screenPoint.getX(), screenPoint.getY() - 15, maxWidth + 8, maxHeight); Color fillColor = new Color(250, 250, 50, 30); g2.setPaint(fillColor); g2.fill(inputBox); g2.setColor(Color.ORANGE); g2.drawRect((int) screenPoint.getX(), (int) screenPoint.getY() - 15, maxWidth + 8, maxHeight); } // g2.drawString(text == null ? "" : text, (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3); } g2.setColor(oldColor); } }
From source file:fr.fg.server.core.TerritoryManager.java
private static BufferedImage createTerritoryMap(int idSector) { List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector)); float[][] points = new float[areas.size()][2]; int[] dominatingAllies = new int[areas.size()]; int i = 0;//w ww . ja va2 s .c om for (Area area : areas) { points[i][0] = area.getX() * MAP_SCALE; points[i][1] = area.getY() * MAP_SCALE; dominatingAllies[i] = area.getIdDominatingAlly(); i++; } Hull hull = new Hull(points); MPolygon hullPolygon = hull.getRegion(); float[][] newPoints = new float[points.length + hullPolygon.count()][2]; System.arraycopy(points, 0, newPoints, 0, points.length); float[][] hullCoords = hullPolygon.getCoords(); for (i = 0; i < hullPolygon.count(); i++) { double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]); double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]); newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE)); newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE)); } points = newPoints; Voronoi voronoi = new Voronoi(points); Delaunay delaunay = new Delaunay(points); // Dcoupage en rgions MPolygon[] regions = voronoi.getRegions(); // Calcule le rayon de la galaxie int radius = 0; for (Area area : areas) { radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY()); } radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE; int diameter = 2 * radius + 1; // Construit l'image avec les quadrants BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) territoriesImage.getGraphics(); // Affecte une couleur chaque alliance HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>(); for (Area area : areas) { int idDominatingAlly = area.getIdDominatingAlly(); if (idDominatingAlly != 0) alliesColors.put(idDominatingAlly, Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]); } Polygon[] polygons = new Polygon[regions.length]; for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] != 0) { polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3); } } // Dessine tous les secteurs g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0) continue; Polygon p = polygons[i]; // Dessine le polygone g.setColor(alliesColors.get(dominatingAllies[i])); g.fill(p); // Rempli les espaces entre les polygones adjacents qui // correspondent au territoire d'une mme alliance int[] linkedRegions = delaunay.getLinked(i); for (int j = 0; j < linkedRegions.length; j++) { int linkedRegion = linkedRegions[j]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { if (linkedRegion <= i) continue; float[][] coords1 = regions[i].getCoords(); float[][] coords2 = regions[linkedRegion].getCoords(); int junctionIndex = 0; int[][] junctions = new int[2][2]; search: for (int k = 0; k < coords1.length; k++) { for (int l = 0; l < coords2.length; l++) { if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) { junctions[junctionIndex][0] = k; junctions[junctionIndex][1] = l; junctionIndex++; if (junctionIndex == 2) { int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]], polygons[linkedRegion].xpoints[junctions[0][1]], polygons[linkedRegion].xpoints[junctions[1][1]], polygons[i].xpoints[junctions[1][0]], }; int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]], polygons[linkedRegion].ypoints[junctions[0][1]], polygons[linkedRegion].ypoints[junctions[1][1]], polygons[i].ypoints[junctions[1][0]], }; Polygon border = new Polygon(xpts, ypts, 4); g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); g.fill(border); g.draw(border); break search; } break; } } } } } } // Dessine des lignes de contours des territoires g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0) continue; g.setStroke(new BasicStroke(1.5f)); g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter()); float[][] coords1 = regions[i].getCoords(); lines: for (int j = 0; j < coords1.length; j++) { int[] linkedRegions = delaunay.getLinked(i); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { float[][] coords2 = regions[linkedRegion].getCoords(); for (int m = 0; m < coords2.length; m++) { if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1] && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1) % coords2.length][0] && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1) % coords2.length][1]) || (coords1[(j + 1) % coords1.length][0] == coords2[(m - 1 + coords2.length) % coords2.length][0] && coords1[(j + 1) % coords1.length][1] == coords2[(m - 1 + coords2.length) % coords2.length][1]))) { continue lines; } } } } g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]), Math.round(polygons[i].xpoints[(j + 1) % coords1.length]), Math.round(polygons[i].ypoints[(j + 1) % coords1.length])); } for (int j = 0; j < coords1.length; j++) { int neighbours = 0; int lastNeighbourRegion = -1; int neighbourCoordsIndex = -1; int[] linkedRegions = delaunay.getLinked(i); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { float[][] coords2 = regions[linkedRegion].getCoords(); for (int m = 0; m < coords2.length; m++) { if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) { neighbours++; lastNeighbourRegion = linkedRegion; neighbourCoordsIndex = m; break; } } } } if (neighbours == 1) { g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]), Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]), Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex])); } } } BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); g = (Graphics2D) finalImage.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f)); g.drawImage(territoriesImage, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); // Charge la police pour afficher le nom des alliances try { Font textFont = Font.createFont(Font.TRUETYPE_FONT, Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf")); textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD); g.setFont(textFont); } catch (Exception e) { LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e); } FontMetrics fm = g.getFontMetrics(); ArrayList<Integer> closedRegions = new ArrayList<Integer>(); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0 || closedRegions.contains(i)) continue; ArrayList<Integer> allyRegions = new ArrayList<Integer>(); ArrayList<Integer> openRegions = new ArrayList<Integer>(); openRegions.add(i); while (openRegions.size() > 0) { int currentRegion = openRegions.remove(0); allyRegions.add(currentRegion); closedRegions.add(currentRegion); int[] linkedRegions = delaunay.getLinked(currentRegion); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion) || allyRegions.contains(linkedRegion)) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) openRegions.add(linkedRegion); } } Area area = areas.get(i); long xsum = 0; long ysum = 0; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); area = areas.get(allyRegion); xsum += area.getX(); ysum += area.getY(); } int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1; int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1; ; Point point = new Point(x, y); boolean validLocation = false; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); if (polygons[allyRegion].contains(point)) { validLocation = true; break; } } if (validLocation) { if (allyRegions.size() == 1) y -= 14; } else { int xmid = (int) (xsum / allyRegions.size()); int ymid = (int) (ysum / allyRegions.size()); area = areas.get(i); int dx = area.getX() - xmid; int dy = area.getY() - ymid; int distance = dx * dx + dy * dy; int nearestAreaIndex = i; int nearestDistance = distance; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); area = areas.get(allyRegion); dx = area.getX() - xmid; dy = area.getY() - ymid; distance = dx * dx + dy * dy; if (distance < nearestDistance) { nearestAreaIndex = allyRegion; nearestDistance = distance; } } area = areas.get(nearestAreaIndex); x = area.getX() * MAP_SCALE + radius + 1; y = -area.getY() * MAP_SCALE + radius - 13; } // Dessine le tag de l'alliance String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]"; g.setColor(Color.BLACK); g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y); g.setColor(alliesColors.get(dominatingAllies[i])); g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y); } return finalImage; }
From source file:org.esa.beam.visat.toolviews.stat.StatisticsPanel.java
private JPanel createStatPanel(Stx stx, final Mask regionalMask, final Mask qualityMask, int stxIdx, RasterDataNode raster) {//from w ww . j a v a2 s. c o m final Histogram histogram = stx.getHistogram(); final int row = stxIdx + 1; // account for header boolean includeFileMetaData = statisticsCriteriaPanel.isIncludeFileMetaData(); boolean includeMaskMetaData = statisticsCriteriaPanel.isIncludeMaskMetaData(); boolean includeBandMetaData = statisticsCriteriaPanel.isIncludeBandMetaData(); boolean includeBinningInfo = statisticsCriteriaPanel.isIncludeBinningInfo(); ; boolean includeTimeMetaData = statisticsCriteriaPanel.isIncludeTimeMetaData(); boolean isIncludeTimeSeriesMetaData = statisticsCriteriaPanel.isIncludeTimeSeriesMetaData(); boolean includeProjectionParameters = statisticsCriteriaPanel.isIncludeProjectionParameters(); boolean includeColumnBreaks = statisticsCriteriaPanel.isIncludeColBreaks(); // Initialize all spreadsheet table indices to -1 (default don't use value) if (stxIdx == 0 || metaDataFieldsHashMap == null || primaryStatisticsFieldsHashMap == null) { initHashMaps(); } XIntervalSeries histogramSeries = new XIntervalSeries("Histogram"); double histDomainBounds[] = { histogram.getLowValue(0), histogram.getHighValue(0) }; double histRangeBounds[] = { Double.NaN, Double.NaN }; if (!fixedHistDomainAllPlots || (fixedHistDomainAllPlots && !fixedHistDomainAllPlotsInitialized)) { if (!statisticsCriteriaPanel.isLogMode()) { if (statisticsCriteriaPanel.plotsThreshDomainSpan()) { if (statisticsCriteriaPanel.plotsThreshDomainLow() >= 0.1) { histDomainBounds[0] = histogram .getPTileThreshold((statisticsCriteriaPanel.plotsThreshDomainLow()) / 100)[0]; } if (statisticsCriteriaPanel.plotsThreshDomainHigh() <= 99.9) { histDomainBounds[1] = histogram .getPTileThreshold(statisticsCriteriaPanel.plotsThreshDomainHigh() / 100)[0]; } } else if (statisticsCriteriaPanel.plotsDomainSpan()) { if (!Double.isNaN(statisticsCriteriaPanel.plotsDomainLow())) { histDomainBounds[0] = statisticsCriteriaPanel.plotsDomainLow(); } if (!Double.isNaN(statisticsCriteriaPanel.plotsDomainHigh())) { histDomainBounds[1] = statisticsCriteriaPanel.plotsDomainHigh(); } } } else { histDomainBounds[0] = histogram.getBinLowValue(0, 0); histDomainBounds[1] = histogram.getHighValue(0); } // if (!LogMode && plotsThreshDomainSpan && plotsThreshDomainLow >= 0.1 && plotsThreshDomainHigh <= 99.9) { // histDomainBounds[0] = histogram.getPTileThreshold((plotsThreshDomainLow) / 100)[0]; // histDomainBounds[1] = histogram.getPTileThreshold(plotsThreshDomainHigh / 100)[0]; // // } else { // histDomainBounds[0] = histogram.getBinLowValue(0, 0); // histDomainBounds[1] = histogram.getHighValue(0); // } if (fixedHistDomainAllPlots && !fixedHistDomainAllPlotsInitialized) { histDomainBoundsAllPlots[0] = histDomainBounds[0]; histDomainBoundsAllPlots[1] = histDomainBounds[1]; fixedHistDomainAllPlotsInitialized = true; } } else { histDomainBounds[0] = histDomainBoundsAllPlots[0]; histDomainBounds[1] = histDomainBoundsAllPlots[1]; } int[] bins = histogram.getBins(0); for (int j = 0; j < bins.length; j++) { histogramSeries.add(histogram.getBinLowValue(0, j), histogram.getBinLowValue(0, j), j < bins.length - 1 ? histogram.getBinLowValue(0, j + 1) : histogram.getHighValue(0), bins[j]); } String logTitle = (statisticsCriteriaPanel.isLogMode()) ? "Log10 of " : ""; ChartPanel histogramPanel = createChartPanel(histogramSeries, logTitle + raster.getName() + " (" + raster.getUnit() + ")", "Frequency in #Pixels", new Color(0, 0, 127), histDomainBounds, histRangeBounds); // histogramPanel.setPreferredSize(new Dimension(300, 200)); if (statisticsCriteriaPanel.exactPlotSize()) { histogramPanel.setMinimumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(), statisticsCriteriaPanel.plotSizeHeight())); histogramPanel.setPreferredSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(), statisticsCriteriaPanel.plotSizeHeight())); histogramPanel.setMaximumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(), statisticsCriteriaPanel.plotSizeHeight())); } else { histogramPanel.setMinimumSize(new Dimension(plotMinWidth, plotMinHeight)); histogramPanel.setPreferredSize(new Dimension(plotMinWidth, plotMinHeight)); } XIntervalSeries percentileSeries = new XIntervalSeries("Percentile"); // if (1 == 2 && LogMode) { // percentileSeries.add(0, // 0, // 1, // Math.pow(10, histogram.getLowValue(0))); // for (int j = 1; j < 99; j++) { // percentileSeries.add(j, // j, // j + 1, // Math.pow(10, histogram.getPTileThreshold(j / 100.0)[0])); // } // percentileSeries.add(99, // 99, // 100, // Math.pow(10, histogram.getHighValue(0))); // // } else { // percentileSeries.add(0, // 0, // 0.25, // histogram.getLowValue(0)); // // for (double j = 0.25; j < 99.75; j += .25) { // percentileSeries.add(j, // j, // j + 1, // histogram.getPTileThreshold(j / 100.0)[0]); // } // percentileSeries.add(99.75, // 99.75, // 100, // histogram.getHighValue(0)); // } // // double fraction = 0; // for (int j = 0; j < bins.length; j++) { // // fraction = (1.0) * j / bins.length; // // if (fraction > 0 && fraction < 1) { // percentileSeries.add(histogram.getBinLowValue(0, j), // histogram.getBinLowValue(0, j), // j < bins.length - 1 ? histogram.getBinLowValue(0, j + 1) : histogram.getHighValue(0), // histogram.getPTileThreshold(fraction)[0]); // } // // // } // // double test = fraction; double[] percentileDomainBounds = { Double.NaN, Double.NaN }; double[] percentileRangeBounds = { Double.NaN, Double.NaN }; ChartPanel percentilePanel = null; if (invertPercentile) { double increment = .01; for (double j = 0; j < 100; j += increment) { double fraction = j / 100.0; double nextFraction = (j + increment) / 100.0; if (fraction > 0.0 && fraction < 1.0 && nextFraction > 0.0 && nextFraction < 1.0) { double thresh = histogram.getPTileThreshold(fraction)[0]; double nextThresh = histogram.getPTileThreshold(nextFraction)[0]; percentileSeries.add(thresh, thresh, nextThresh, j); } } if (!statisticsCriteriaPanel.isLogMode()) { percentileDomainBounds[0] = histDomainBounds[0]; percentileDomainBounds[1] = histDomainBounds[1]; } percentileRangeBounds[0] = 0; percentileRangeBounds[1] = 100; percentilePanel = createScatterChartPanel(percentileSeries, logTitle + raster.getName() + " (" + raster.getUnit() + ")", "Percent Threshold", new Color(0, 0, 0), percentileDomainBounds, percentileRangeBounds); } else { percentileSeries.add(0, 0, 0.25, histogram.getLowValue(0)); for (double j = 0.25; j < 99.75; j += .25) { percentileSeries.add(j, j, j + 1, histogram.getPTileThreshold(j / 100.0)[0]); } percentileSeries.add(99.75, 99.75, 100, histogram.getHighValue(0)); percentileDomainBounds[0] = 0; percentileDomainBounds[1] = 100; percentileRangeBounds[0] = histDomainBounds[0]; percentileRangeBounds[1] = histDomainBounds[1]; percentilePanel = createScatterChartPanel(percentileSeries, "Percent_Threshold", logTitle + raster.getName() + " (" + raster.getUnit() + ")", new Color(0, 0, 0), percentileDomainBounds, percentileRangeBounds); } // percentilePanel.setPreferredSize(new Dimension(300, 200)); if (statisticsCriteriaPanel.exactPlotSize()) { percentilePanel.setMinimumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(), statisticsCriteriaPanel.plotSizeHeight())); percentilePanel.setPreferredSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(), statisticsCriteriaPanel.plotSizeHeight())); percentilePanel.setMaximumSize(new Dimension(statisticsCriteriaPanel.plotSizeWidth(), statisticsCriteriaPanel.plotSizeHeight())); } else { percentilePanel.setMinimumSize(new Dimension(plotMinWidth, plotMinHeight)); percentilePanel.setPreferredSize(new Dimension(plotMinWidth, plotMinHeight)); } int size = raster.getRasterHeight() * raster.getRasterWidth(); int validPixelCount = histogram.getTotals()[0]; int dataRows = 0; // new Object[]{"RasterSize(Pixels)", size}, // new Object[]{"SampleSize(Pixels)", histogram.getTotals()[0]}, Object[][] totalPixels = null; if (statisticsCriteriaPanel.includeTotalPixels()) { int totalPixelCount = stx.getRawTotal(); double percentFilled = (totalPixelCount > 0) ? (1.0 * validPixelCount / totalPixelCount) : 0; totalPixels = new Object[][] { new Object[] { "Regional_Pixels", stx.getRawTotal() }, new Object[] { "Valid_Pixels", validPixelCount }, new Object[] { "Fraction_Valid", percentFilled } }; } else { totalPixels = new Object[][] { new Object[] { "Valid_Pixels", validPixelCount } }; } dataRows += totalPixels.length; Object[][] firstData = new Object[][] { new Object[] { "Mean", stx.getMean() } }; dataRows += firstData.length; Object[][] minMaxData = null; if (statisticsCriteriaPanel.includeMinMax()) { minMaxData = new Object[][] { new Object[] { "Minimum", stx.getMinimum() }, new Object[] { "Maximum", stx.getMaximum() } }; dataRows += minMaxData.length; } Object[] medianObject = null; if (statisticsCriteriaPanel.includeMedian()) { medianObject = new Object[] { "Median", stx.getMedianRaster() }; dataRows++; } Object[][] secondData = new Object[][] { new Object[] { "Standard_Deviation", stx.getStandardDeviation() }, new Object[] { "Variance", getVariance(stx) }, new Object[] { "Coefficient_of_Variation", getCoefficientOfVariation(stx) } }; dataRows += secondData.length; Object[][] binningInfo = null; if (statisticsCriteriaPanel.isIncludeBinningInfo()) { binningInfo = new Object[][] { new Object[] { "Total_Bins", histogram.getNumBins()[0] }, new Object[] { "Bin_Width", getBinSize(histogram) }, new Object[] { "Bin_Min", histogram.getLowValue(0) }, new Object[] { "Bin_Max", histogram.getHighValue(0) } }; dataRows += binningInfo.length; } Object[][] histogramStats = null; if (statisticsCriteriaPanel.includeHistogramStats()) { if (statisticsCriteriaPanel.isLogMode()) { histogramStats = new Object[][] { new Object[] { "Mean(LogBinned)", Math.pow(10, histogram.getMean()[0]) }, new Object[] { "Median(LogBinned)", Math.pow(10, stx.getMedian()) }, new Object[] { "StandardDeviation(LogBinned)", Math.pow(10, histogram.getStandardDeviation()[0]) } }; } else { histogramStats = new Object[][] { new Object[] { "Mean(Binned)", histogram.getMean()[0] }, new Object[] { "Median(Binned)", stx.getMedian() }, new Object[] { "StandardDeviation(Binned)", histogram.getStandardDeviation()[0] } }; } dataRows += histogramStats.length; } Object[][] percentData = new Object[statisticsCriteriaPanel.getPercentThresholdsList().size()][]; for (int i = 0; i < statisticsCriteriaPanel.getPercentThresholdsList().size(); i++) { int value = statisticsCriteriaPanel.getPercentThresholdsList().get(i); double percent = value / 100.0; String percentString = Integer.toString(value); Object[] pTileThreshold; if (statisticsCriteriaPanel.isLogMode()) { pTileThreshold = new Object[] { percentString + "%Threshold(Log)", Math.pow(10, histogram.getPTileThreshold(percent)[0]) }; } else { pTileThreshold = new Object[] { percentString + "%Threshold", histogram.getPTileThreshold(percent)[0] }; } percentData[i] = pTileThreshold; } dataRows += percentData.length; Object[][] tableData = new Object[dataRows][]; int tableDataIdx = 0; if (totalPixels != null) { for (int i = 0; i < totalPixels.length; i++) { tableData[tableDataIdx] = totalPixels[i]; tableDataIdx++; } } if (firstData != null) { for (int i = 0; i < firstData.length; i++) { tableData[tableDataIdx] = firstData[i]; tableDataIdx++; } } if (medianObject != null) { tableData[tableDataIdx] = medianObject; tableDataIdx++; } if (minMaxData != null) { for (int i = 0; i < minMaxData.length; i++) { tableData[tableDataIdx] = minMaxData[i]; tableDataIdx++; } } if (secondData != null) { for (int i = 0; i < secondData.length; i++) { tableData[tableDataIdx] = secondData[i]; tableDataIdx++; } } if (binningInfo != null) { for (int i = 0; i < binningInfo.length; i++) { tableData[tableDataIdx] = binningInfo[i]; tableDataIdx++; } } if (histogramStats != null) { for (int i = 0; i < histogramStats.length; i++) { tableData[tableDataIdx] = histogramStats[i]; tableDataIdx++; } } if (percentData != null) { for (int i = 0; i < percentData.length; i++) { tableData[tableDataIdx] = percentData[i]; tableDataIdx++; } } numStxFields = tableData.length; int fieldIdx = 0; // Initialize indices if (stxIdx == 0) { primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.FileRefNum, fieldIdx); fieldIdx++; primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.BandName, fieldIdx); fieldIdx++; primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.MaskName, fieldIdx); fieldIdx++; primaryStatisticsFieldsHashMap.put(PrimaryStatisticsFields.QualityMaskName, fieldIdx); fieldIdx++; stxFieldsStartIdx = fieldIdx; fieldIdx += numStxFields; stxFieldsEndIdx = fieldIdx - 1; if (includeBandMetaData) { if (includeColumnBreaks) { metaDataFieldsHashMap.put(MetaDataFields.BandMetaDataBreak, fieldIdx); fieldIdx++; } metaDataFieldsHashMap.put(MetaDataFields.BandName, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.BandUnit, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.BandValidExpression, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.BandDescription, fieldIdx); fieldIdx++; } if (includeMaskMetaData) { if (includeColumnBreaks) { metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskMetaDataBreak, fieldIdx); fieldIdx++; } metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskName, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskDescription, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.RegionalMaskExpression, fieldIdx); fieldIdx++; if (includeColumnBreaks) { metaDataFieldsHashMap.put(MetaDataFields.QualityMaskMetaDataBreak, fieldIdx); fieldIdx++; } metaDataFieldsHashMap.put(MetaDataFields.QualityMaskName, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.QualityMaskDescription, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.QualityMaskExpression, fieldIdx); fieldIdx++; } if (includeTimeMetaData || isIncludeTimeSeriesMetaData) { if (includeColumnBreaks) { metaDataFieldsHashMap.put(MetaDataFields.TimeMetaDataBreak, fieldIdx); fieldIdx++; } if (includeTimeMetaData) { metaDataFieldsHashMap.put(MetaDataFields.StartDate, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.StartTime, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.EndDate, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.EndTime, fieldIdx); fieldIdx++; } if (isIncludeTimeSeriesMetaData) { metaDataFieldsHashMap.put(MetaDataFields.TimeSeriesDate, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.TimeSeriesTime, fieldIdx); fieldIdx++; } } if (includeFileMetaData) { if (includeColumnBreaks) { metaDataFieldsHashMap.put(MetaDataFields.FileMetaDataBreak, fieldIdx); fieldIdx++; } metaDataFieldsHashMap.put(MetaDataFields.FileName, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.FileType, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.FileFormat, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.FileWidth, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.FileHeight, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.Sensor, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.Platform, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.Resolution, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.DayNight, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.Orbit, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.ProcessingVersion, fieldIdx); fieldIdx++; metaDataFieldsHashMap.put(MetaDataFields.Projection, fieldIdx); fieldIdx++; } if (includeProjectionParameters) { metaDataFieldsHashMap.put(MetaDataFields.ProjectionParameters, fieldIdx); fieldIdx++; } } if (statsSpreadsheet == null) { statsSpreadsheet = new Object[numStxRegions + 2][fieldIdx]; // add 1 row to account for the header and 1 more empty row because JTable for some reason displays // only half of the last row when row count is large } String startDateString = ""; String startTimeString = ""; String endDateString = ""; String endTimeString = ""; if (includeTimeMetaData) { ProductData.UTC startDateTimeCorrected; ProductData.UTC endDateTimeCorrected; // correct time (invert start and end time if end time later than start time if (getProduct().getStartTime() != null && getProduct().getEndTime() != null) { if (getProduct().getStartTime().getMJD() <= getProduct().getEndTime().getMJD()) { startDateTimeCorrected = getProduct().getStartTime(); endDateTimeCorrected = getProduct().getEndTime(); } else { startDateTimeCorrected = getProduct().getEndTime(); endDateTimeCorrected = getProduct().getStartTime(); } if (startDateTimeCorrected != null) { String[] startDateTimeStringArray = startDateTimeCorrected.toString().split(" "); if (startDateTimeStringArray.length >= 2) { startDateString = startDateTimeStringArray[0].trim(); startTimeString = startDateTimeStringArray[1].trim(); } } if (endDateTimeCorrected != null) { String[] endDateTimeStringArray = endDateTimeCorrected.toString().split(" "); if (endDateTimeStringArray.length >= 2) { endDateString = endDateTimeStringArray[0].trim(); endTimeString = endDateTimeStringArray[1].trim(); } } } } String timeSeriesDate = ""; String timeSeriesTime = ""; if (isIncludeTimeSeriesMetaData) { String bandName = raster.getName(); String productDateTime = convertBandNameToProductTime(bandName); if (productDateTime != null) { String[] endDateTimeStringArray = productDateTime.split(" "); if (endDateTimeStringArray.length >= 2) { timeSeriesDate = endDateTimeStringArray[0].trim(); timeSeriesTime = endDateTimeStringArray[1].trim(); } } } String maskName = ""; String maskDescription = ""; String maskExpression = ""; if (regionalMask != null) { maskName = regionalMask.getName(); maskDescription = regionalMask.getDescription(); maskExpression = regionalMask.getImageConfig().getValue("expression"); } String qualityMaskName = ""; String qualityMaskDescription = ""; String qualityMaskExpression = ""; if (qualityMask != null) { qualityMaskName = qualityMask.getName(); qualityMaskDescription = qualityMask.getDescription(); qualityMaskExpression = qualityMask.getImageConfig().getValue("expression"); } addFieldToSpreadsheet(row, PrimaryStatisticsFields.FileRefNum, getProduct().getRefNo()); addFieldToSpreadsheet(row, PrimaryStatisticsFields.BandName, raster.getName()); addFieldToSpreadsheet(row, PrimaryStatisticsFields.MaskName, maskName); addFieldToSpreadsheet(row, PrimaryStatisticsFields.QualityMaskName, qualityMaskName); addFieldToSpreadsheet(row, MetaDataFields.TimeMetaDataBreak, COLUMN_BREAK); addFieldToSpreadsheet(row, MetaDataFields.StartDate, startDateString); addFieldToSpreadsheet(row, MetaDataFields.StartTime, startTimeString); addFieldToSpreadsheet(row, MetaDataFields.EndDate, endDateString); addFieldToSpreadsheet(row, MetaDataFields.EndTime, endTimeString); addFieldToSpreadsheet(row, MetaDataFields.TimeSeriesDate, timeSeriesDate); addFieldToSpreadsheet(row, MetaDataFields.TimeSeriesTime, timeSeriesTime); addFieldToSpreadsheet(row, MetaDataFields.FileMetaDataBreak, COLUMN_BREAK); addFieldToSpreadsheet(row, MetaDataFields.FileName, getProduct().getName()); addFieldToSpreadsheet(row, MetaDataFields.FileType, getProduct().getProductType()); addFieldToSpreadsheet(row, MetaDataFields.FileWidth, getProduct().getSceneRasterWidth()); addFieldToSpreadsheet(row, MetaDataFields.FileFormat, getProductFormatName(getProduct())); addFieldToSpreadsheet(row, MetaDataFields.FileHeight, getProduct().getSceneRasterHeight()); addFieldToSpreadsheet(row, MetaDataFields.Sensor, ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_SENSOR_KEYS)); addFieldToSpreadsheet(row, MetaDataFields.Platform, ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_PLATFORM_KEYS)); addFieldToSpreadsheet(row, MetaDataFields.Resolution, ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_RESOLUTION_KEYS)); addFieldToSpreadsheet(row, MetaDataFields.DayNight, ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_DAY_NIGHT_KEYS)); addFieldToSpreadsheet(row, MetaDataFields.Orbit, ProductUtils.getMetaDataOrbit(getProduct())); addFieldToSpreadsheet(row, MetaDataFields.ProcessingVersion, ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_PROCESSING_VERSION_KEYS)); // Determine projection String projection = ""; String projectionParameters = ""; GeoCoding geo = getProduct().getGeoCoding(); // determine if using class CrsGeoCoding otherwise display class if (geo != null) { if (geo instanceof CrsGeoCoding) { projection = geo.getMapCRS().getName().toString() + "(obtained from CrsGeoCoding)"; projectionParameters = geo.getMapCRS().toString().replaceAll("\n", " ").replaceAll(" ", ""); } else if (geo.toString() != null) { String projectionFromMetaData = ProductUtils.getMetaData(getProduct(), ProductUtils.METADATA_POSSIBLE_PROJECTION_KEYS); if (projectionFromMetaData != null && projectionFromMetaData.length() > 0) { projection = projectionFromMetaData + "(obtained from MetaData)"; } else { projection = "unknown (" + geo.getClass().toString() + ")"; } } } addFieldToSpreadsheet(row, MetaDataFields.Projection, projection); addFieldToSpreadsheet(row, MetaDataFields.ProjectionParameters, projectionParameters); addFieldToSpreadsheet(row, MetaDataFields.BandMetaDataBreak, COLUMN_BREAK); addFieldToSpreadsheet(row, MetaDataFields.BandName, raster.getName()); addFieldToSpreadsheet(row, MetaDataFields.BandUnit, raster.getUnit()); addFieldToSpreadsheet(row, MetaDataFields.BandValidExpression, raster.getValidPixelExpression()); addFieldToSpreadsheet(row, MetaDataFields.BandDescription, raster.getDescription()); addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskMetaDataBreak, COLUMN_BREAK); addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskName, maskName); addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskDescription, maskDescription); addFieldToSpreadsheet(row, MetaDataFields.RegionalMaskExpression, maskExpression); addFieldToSpreadsheet(row, MetaDataFields.QualityMaskMetaDataBreak, COLUMN_BREAK); addFieldToSpreadsheet(row, MetaDataFields.QualityMaskName, qualityMaskName); addFieldToSpreadsheet(row, MetaDataFields.QualityMaskDescription, qualityMaskDescription); addFieldToSpreadsheet(row, MetaDataFields.QualityMaskExpression, qualityMaskExpression); // Add Header first time through if (row <= 1) { int k = stxFieldsStartIdx; for (int i = 0; i < tableData.length; i++) { Object value = tableData[i][0]; if (k < statsSpreadsheet[0].length && k <= stxFieldsEndIdx) { statsSpreadsheet[0][k] = value; k++; } } } // account for header as added row if (row < statsSpreadsheet.length) { int k = stxFieldsStartIdx; for (int i = 0; i < tableData.length; i++) { Object value = tableData[i][1]; if (k < statsSpreadsheet[row].length && k <= stxFieldsEndIdx) { statsSpreadsheet[row][k] = value; k++; } } } int numPlots = 0; if (statisticsCriteriaPanel.showPercentPlots()) { numPlots++; } if (statisticsCriteriaPanel.showHistogramPlots()) { numPlots++; } JPanel plotContainerPanel = null; if (numPlots > 0) { plotContainerPanel = new JPanel(new GridLayout(1, numPlots)); if (statisticsCriteriaPanel.showHistogramPlots()) { plotContainerPanel.add(histogramPanel); } if (statisticsCriteriaPanel.showPercentPlots()) { plotContainerPanel.add(percentilePanel); } } TableModel tableModel = new DefaultTableModel(tableData, new String[] { "Name", "Value" }) { @Override public Class<?> getColumnClass(int columnIndex) { return columnIndex == 0 ? String.class : Number.class; } @Override public boolean isCellEditable(int row, int column) { return false; } }; final JTable table = new JTable(tableModel); table.setDefaultRenderer(Number.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (value instanceof Float || value instanceof Double) { setHorizontalTextPosition(RIGHT); setText(getFormattedValue((Number) value)); } return label; } private String getFormattedValue(Number value) { if (value.doubleValue() < 0.001 && value.doubleValue() > -0.001 && value.doubleValue() != 0.0) { return new DecimalFormat("0.####E0").format(value.doubleValue()); } String format = "%." + Integer.toString(statisticsCriteriaPanel.decimalPlaces()) + "f"; return String.format(format, value.doubleValue()); } }); table.addMouseListener(popupHandler); // TEST CODE generically preferred size of each column based on longest expected entry // fails a bit because decimal formatting is not captured // stub of code commented out in case we want to make it work // meanwhile longest entry is being used SEE below // int column0Length = 0; // int column1Length = 0; // FontMetrics fm = table.getFontMetrics(table.getFont()); // for (int rowIndex = 0; rowIndex < table.getRowCount(); rowIndex++) { // String test = table.getValueAt(rowIndex,0).toString(); // int currColumn0Length = fm.stringWidth(table.getValueAt(rowIndex,0).toString()); // if (currColumn0Length > column0Length) { // column0Length = currColumn0Length; // } // // String test2 = table.getValueAt(rowIndex,1).toString(); // int currColumn1Length = fm.stringWidth(table.getValueAt(rowIndex,1).toString()); // if (currColumn1Length > column1Length) { // column1Length = currColumn1Length; // } // } // Set preferred size of each column based on longest expected entry FontMetrics fm = table.getFontMetrics(table.getFont()); TableColumn column = null; int col1PreferredWidth = -1; if (statisticsCriteriaPanel.isLogMode()) { col1PreferredWidth = fm.stringWidth("StandardDeviation(LogBinned):") + 10; } else { col1PreferredWidth = fm.stringWidth("StandardDeviation(Binned):") + 10; } // int col1PreferredWidth = fm.stringWidth("wwwwwwwwwwwwwwwwwwwwwwwwww"); int col2PreferredWidth = fm.stringWidth("1234567890") + 10; int tablePreferredWidth = col1PreferredWidth + col2PreferredWidth; for (int i = 0; i < 2; i++) { column = table.getColumnModel().getColumn(i); if (i == 0) { column.setPreferredWidth(col1PreferredWidth); column.setMaxWidth(col1PreferredWidth); } else { column.setPreferredWidth(col2PreferredWidth); } } JPanel textContainerPanel = new JPanel(new BorderLayout(2, 2)); // textContainerPanel.setBackground(Color.WHITE); textContainerPanel.add(table, BorderLayout.CENTER); textContainerPanel.addMouseListener(popupHandler); JPanel statsPane = GridBagUtils.createPanel(); GridBagConstraints gbc = GridBagUtils.createConstraints(""); gbc.gridy = 0; gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.weightx = 1; gbc.weighty = 1; Dimension dim = table.getPreferredSize(); table.setPreferredSize(new Dimension(tablePreferredWidth, dim.height)); statsPane.add(table, gbc); statsPane.setPreferredSize(new Dimension(tablePreferredWidth, dim.height)); JPanel plotsPane = null; if (plotContainerPanel != null) { plotsPane = GridBagUtils.createPanel(); plotsPane.setBackground(Color.WHITE); // plotsPane.setBorder(UIUtils.createGroupBorder(" ")); /*I18N*/ GridBagConstraints gbcPlots = GridBagUtils.createConstraints(""); gbcPlots.gridy = 0; if (statisticsCriteriaPanel.exactPlotSize()) { gbcPlots.fill = GridBagConstraints.NONE; } else { gbcPlots.fill = GridBagConstraints.BOTH; } gbcPlots.anchor = GridBagConstraints.NORTHWEST; gbcPlots.weightx = 0.5; gbcPlots.weighty = 1; plotsPane.add(plotContainerPanel, gbcPlots); } JPanel mainPane = GridBagUtils.createPanel(); mainPane.setBorder(UIUtils.createGroupBorder(getSubPanelTitle(regionalMask, qualityMask, raster))); /*I18N*/ GridBagConstraints gbcMain = GridBagUtils.createConstraints(""); gbcMain.gridx = 0; gbcMain.gridy = 0; gbcMain.anchor = GridBagConstraints.NORTHWEST; if (plotsPane != null) { gbcMain.fill = GridBagConstraints.VERTICAL; gbcMain.weightx = 0; } else { gbcMain.fill = GridBagConstraints.BOTH; gbcMain.weightx = 1; } if (statisticsCriteriaPanel.showStatsList()) { gbcMain.weighty = 1; mainPane.add(statsPane, gbcMain); gbcMain.gridx++; } gbcMain.weightx = 1; gbcMain.weighty = 1; gbcMain.fill = GridBagConstraints.BOTH; if (plotsPane != null) { mainPane.add(plotsPane, gbcMain); } return mainPane; }
From source file:com.projity.contrib.calendar.JXXMonthView.java
/** * {@inheritDoc}/*from w w w. java2 s. com*/ */ 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: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 {//from w w w . j a va 2 s . c om 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); }