List of usage examples for java.awt FontMetrics stringWidth
public int stringWidth(String str)
From source file:Base64.java
/** * Draws a line on the screen at the specified index. Default is green. * <p/>//from w ww . j ava 2 s. c o m * Available colours: red, green, cyan, purple, white. * * @param render The Graphics object to be used. * @param row The index where you want the text. * @param text The text you want to render. Colours can be set like [red]. */ public static void drawLine(Graphics render, int row, String text) { FontMetrics metrics = render.getFontMetrics(); int height = metrics.getHeight() + 4; // height + gap int y = row * height + 15 + 19; String[] texts = text.split("\\["); int xIdx = 7; Color cur = Color.GREEN; for (String t : texts) { for (@SuppressWarnings("unused") String element : COLOURS_STR) { // String element = COLOURS_STR[i]; // Don't search for a starting '[' cause it they don't exists. // we split on that. int endIdx = t.indexOf(']'); if (endIdx != -1) { String colorName = t.substring(0, endIdx); if (COLOR_MAP.containsKey(colorName)) { cur = COLOR_MAP.get(colorName); } else { try { Field f = Color.class.getField(colorName); int mods = f.getModifiers(); if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) { cur = (Color) f.get(null); COLOR_MAP.put(colorName, cur); } } catch (Exception ignored) { } } t = t.replace(colorName + "]", ""); } } render.setColor(Color.BLACK); render.drawString(t, xIdx, y + 1); render.setColor(cur); render.drawString(t, xIdx, y); xIdx += metrics.stringWidth(t); } }
From source file:edu.ku.brc.ui.tmanfe.SpreadSheet.java
/** * //from w ww .j av a2 s .c om */ protected void buildSpreadsheet() { this.setShowGrid(true); int numRows = model.getRowCount(); scrollPane = new JScrollPane(this, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final SpreadSheet ss = this; JButton cornerBtn = UIHelper.createIconBtn("Blank", IconManager.IconSize.Std16, "SelectAll", new ActionListener() { public void actionPerformed(ActionEvent ae) { ss.selectAll(); } }); cornerBtn.setEnabled(true); scrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, cornerBtn); // Allows row and collumn selections to exit at the same time setCellSelectionEnabled(true); setRowSelectionAllowed(true); setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); addMouseListener(new MouseAdapter() { /* (non-Javadoc) * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent) */ @SuppressWarnings("synthetic-access") @Override public void mouseReleased(MouseEvent e) { // XXX For Java 5 Bug prevRowSelInx = getSelectedRow(); prevColSelInx = getSelectedColumn(); if (e.getClickCount() == 2) { int rowIndexStart = getSelectedRow(); int colIndexStart = getSelectedColumn(); ss.editCellAt(rowIndexStart, colIndexStart); if (ss.getEditorComponent() != null && ss.getEditorComponent() instanceof JTextComponent) { ss.getEditorComponent().requestFocus(); final JTextComponent txtComp = (JTextComponent) ss.getEditorComponent(); String txt = txtComp.getText(); FontMetrics fm = txtComp.getFontMetrics(txtComp.getFont()); int x = e.getPoint().x - ss.getEditorComponent().getBounds().x - 1; int prevWidth = 0; for (int i = 0; i < txt.length(); i++) { int width = fm.stringWidth(txt.substring(0, i)); int basePlusHalf = prevWidth + (int) (((width - prevWidth) / 2) + 0.5); //System.out.println(prevWidth + " X[" + x + "] " + width+" ["+txt.substring(0, i)+"] " + i + " " + basePlusHalf); //System.out.println(" X[" + x + "] " + prevWidth + " - "+ basePlusHalf+" - " + width+" ["+txt.substring(0, i)+"] " + i); if (x < width) { // Clearing the selection is needed for Window for some reason final int inx = i + (x <= basePlusHalf ? -1 : 0); SwingUtilities.invokeLater(new Runnable() { @SuppressWarnings("synthetic-access") public void run() { txtComp.setSelectionStart(0); txtComp.setSelectionEnd(0); txtComp.setCaretPosition(inx > 0 ? inx : 0); } }); break; } prevWidth = width; } } } } }); // Create a row-header to display row numbers. // This row-header is made of labels whose Borders, // Foregrounds, Backgrounds, and Fonts must be // the one used for the table column headers. // Also ensure that the row-header labels and the table // rows have the same height. //i have no idea WHY this has to be called. i rearranged //the table and find replace panel, // i started getting an array index out of //bounds on the column header ON MAC ONLY. //tried firing this off, first and it fixed the problem.//meg this.getModel().fireTableStructureChanged(); /* * Create the Row Header Panel */ rowHeaderPanel = new JPanel((LayoutManager) null); if (getColumnModel().getColumnCount() > 0) { TableColumn column = getColumnModel().getColumn(0); TableCellRenderer renderer = getTableHeader().getDefaultRenderer(); if (renderer == null) { renderer = column.getHeaderRenderer(); } Component cellRenderComp = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false, false, -1, 0); cellFont = cellRenderComp.getFont(); } else { cellFont = (new JLabel()).getFont(); } // Calculate Row Height cellBorder = (Border) UIManager.getDefaults().get("TableHeader.cellBorder"); Insets insets = cellBorder.getBorderInsets(tableHeader); FontMetrics metrics = getFontMetrics(cellFont); rowHeight = insets.bottom + metrics.getHeight() + insets.top; rowLabelWidth = metrics.stringWidth("9999") + insets.right + insets.left; Dimension dim = new Dimension(rowLabelWidth, rowHeight * numRows); rowHeaderPanel.setPreferredSize(dim); // need to call this when no layout manager is used. rhCellMouseAdapter = new RHCellMouseAdapter(this); // Adding the row header labels for (int ii = 0; ii < numRows; ii++) { addRow(ii, ii + 1, false); } JViewport viewPort = new JViewport(); dim.height = rowHeight * numRows; viewPort.setViewSize(dim); viewPort.setView(rowHeaderPanel); scrollPane.setRowHeader(viewPort); // Experimental from the web, but I think it does the trick. addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (!ss.isEditing() && !e.isActionKey() && !e.isControlDown() && !e.isMetaDown() && !e.isAltDown() && e.getKeyCode() != KeyEvent.VK_SHIFT && e.getKeyCode() != KeyEvent.VK_TAB && e.getKeyCode() != KeyEvent.VK_ENTER) { log.error("Grabbed the event as input"); int rowIndexStart = getSelectedRow(); int colIndexStart = getSelectedColumn(); if (rowIndexStart == -1 || colIndexStart == -1) return; ss.editCellAt(rowIndexStart, colIndexStart); Component c = ss.getEditorComponent(); if (c instanceof JTextComponent) ((JTextComponent) c).setText(""); } } }); resizeAndRepaint(); // Taken from a JavaWorld Example (But it works) KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false); KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false); KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false); Action ssAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { SpreadSheet.this.actionPerformed(e); } }; getInputMap().put(cut, "Cut"); getActionMap().put("Cut", ssAction); getInputMap().put(copy, "Copy"); getActionMap().put("Copy", ssAction); getInputMap().put(paste, "Paste"); getActionMap().put("Paste", ssAction); ((JMenuItem) UIRegistry.get(UIRegistry.COPY)).addActionListener(this); ((JMenuItem) UIRegistry.get(UIRegistry.CUT)).addActionListener(this); ((JMenuItem) UIRegistry.get(UIRegistry.PASTE)).addActionListener(this); setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED); }
From source file:com.moviejukebox.plugin.DefaultImagePlugin.java
private BufferedImage drawText(BufferedImage bi, String outputText, boolean verticalAlign) { Graphics2D g2d = bi.createGraphics(); g2d.setFont(new Font(textFont, Font.BOLD, textFontSize)); FontMetrics fm = g2d.getFontMetrics(); int textWidth = fm.stringWidth(outputText); int imageWidth = bi.getWidth(); int imageHeight = bi.getHeight(); int leftAlignment; int topAlignment; if (textAlignment.equalsIgnoreCase(LEFT)) { leftAlignment = textOffset;/* w w w .j av a 2s. c om*/ } else if (textAlignment.equalsIgnoreCase(RIGHT)) { leftAlignment = imageWidth - textWidth - textOffset; } else { leftAlignment = (imageWidth / 2) - (textWidth / 2); } if (verticalAlign) { // Align the text to the top topAlignment = fm.getHeight() - 10; } else { // Align the text to the bottom topAlignment = imageHeight - 10; } // Create the drop shadow if (StringUtils.isNotBlank(textFontShadow)) { g2d.setColor(getColor(textFontShadow, Color.DARK_GRAY)); g2d.drawString(outputText, leftAlignment + 2, topAlignment + 2); } // Create the text itself g2d.setColor(getColor(textFontColor, Color.LIGHT_GRAY)); g2d.drawString(outputText, leftAlignment, topAlignment); g2d.dispose(); return bi; }
From source file:forseti.JUtil.java
public static synchronized Image generarImagenMensaje(String mensaje, String nombreFuente, int tamanioFuente) { Frame f = new Frame(); f.addNotify();//w w w .j a v a 2 s .co m GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); env.getAvailableFontFamilyNames(); Font fuente = new Font(nombreFuente, Font.PLAIN, tamanioFuente); FontMetrics medidas = f.getFontMetrics(fuente); int anchoMensaje = medidas.stringWidth(mensaje); int lineaBaseX = anchoMensaje / 10; int ancho = anchoMensaje + 2 * (lineaBaseX + tamanioFuente); int alto = tamanioFuente * 7 / 2; int lineaBaseY = alto * 8 / 10; Image imagenMensaje = f.createImage(ancho, alto); Graphics2D g2d = (Graphics2D) imagenMensaje.getGraphics(); g2d.setFont(fuente); g2d.translate(lineaBaseX, lineaBaseY); g2d.setPaint(Color.lightGray); AffineTransform origTransform = g2d.getTransform(); g2d.shear(-0.95, 0); g2d.scale(1, 3); g2d.drawString(mensaje, 0, 0); g2d.setTransform(origTransform); g2d.setPaint(Color.black); g2d.drawString(mensaje, 0, 0); return (imagenMensaje); }
From source file:pl.edu.icm.visnow.geometries.viewer3d.Display3DPanel.java
public void drawLocal2D(J3DGraphics2D vGraphics, LocalToWindow ltw, int w, int h) { if (titles == null || titles.isEmpty()) { return;// ww w .j a v a 2 s. c o m } Font f = vGraphics.getFont(); Color c = vGraphics.getColor(); for (Title title : titles) { float fh = h * title.getFontHeight(); if (fh < 5) { fh = 5; } Font actualFont = title.getFont().deriveFont(fh); vGraphics.setFont(actualFont); FontMetrics fm = vGraphics.getFontMetrics(); int strWidth = fm.stringWidth(title.getTitle()); vGraphics.setColor(title.getColor()); int xPos = w / 50; if (title.getHorizontalPosition() == Title.CENTER) { xPos = (w - strWidth) / 2; } if (title.getHorizontalPosition() == Title.RIGHT) { xPos = w - strWidth - getWidth() / 50; } vGraphics.drawString(title.getTitle(), xPos, (int) (effectiveHeight * title.getVerticalPosition()) + actualFont.getSize()); } vGraphics.setFont(f); vGraphics.setColor(c); }
From source file:com.projity.contrib.calendar.JXXMonthView.java
/** * Calculates size information necessary for laying out the month view. */// w w w . j a v a 2 s. com private void update() { // Loop through year and get largest representation of the month. // Keep track of the longest month so we can loop through it to // determine the width of a date box. int currDays; int longestMonth = 0; int daysInLongestMonth = 0; int currWidth; int longestMonthWidth = 0; // We use a bold font for figuring out size constraints since // it's larger and flaggedDates will be noted in this style. _derivedFont = getFont().deriveFont(Font.BOLD); _baselineFont = getFont().deriveFont(Font.HANGING_BASELINE); FontMetrics fm = getFontMetrics(_derivedFont); _cal.set(Calendar.MONTH, _cal.getMinimum(Calendar.MONTH)); _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < _cal.getMaximum(Calendar.MONTH); i++) { currWidth = fm.stringWidth(_monthsOfTheYear[i]); if (currWidth > longestMonthWidth) { longestMonthWidth = currWidth; } currDays = _cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (currDays > daysInLongestMonth) { longestMonth = _cal.get(Calendar.MONTH); daysInLongestMonth = currDays; } _cal.add(Calendar.MONTH, 1); } // Loop through longest month and get largest representation of the day // of the month. _cal.set(Calendar.MONTH, longestMonth); _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); _boxHeight = fm.getHeight(); for (int i = 0; i < daysInLongestMonth; i++) { currWidth = fm.stringWidth(_dayOfMonthFormatter.format(_cal.getTime())); if (currWidth > _boxWidth) { _boxWidth = currWidth; } _cal.add(Calendar.DAY_OF_MONTH, 1); } // Modify _boxWidth if month string is longer _dim.width = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK; if (_dim.width < longestMonthWidth) { double diff = longestMonthWidth - _dim.width; _boxWidth += Math.ceil(diff / (double) DAYS_IN_WEEK); _dim.width = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK; } // Keep track of calendar width and height for use later. _calendarWidth = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK; _calendarHeight = (_boxPaddingY + _boxHeight + _boxPaddingY) * 8; // Calculate minimum width/height for the component. _dim.height = (_calendarHeight * _minCalRows) + (CALENDAR_SPACING * (_minCalRows - 1)); _dim.width = (_calendarWidth * _minCalCols) + (CALENDAR_SPACING * (_minCalCols - 1)); // Add insets to the dimensions. Insets insets = getInsets(); _dim.width += insets.left + insets.right; _dim.height += insets.top + insets.bottom; // Restore calendar. _cal.setTimeInMillis(_firstDisplayedDate); }
From source file:org.gumtree.vis.awt.JChartPanel.java
@Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.ALT_MASK) != 0) { double xNew = ChartMaskingUtilities.translateScreenX(e.getX(), getScreenDataArea(), getChart()); double yNew = ChartMaskingUtilities.translateScreenY(e.getY(), getScreenDataArea(), getChart(), 0); addMarker(xNew, yNew, null);/*from w w w .j a v a2 s . c o m*/ } else if (isTextInputEnabled) { if (!textInputFlag) { boolean newTextEnabled = selectedTextWrapper == null; if (selectedTextWrapper != null) { Point2D screenXY = ChartMaskingUtilities.translateChartPoint( new Point2D.Double(selectedTextWrapper.getMinX(), selectedTextWrapper.getMinY()), getScreenDataArea(), getChart()); Rectangle2D screenRect = new Rectangle2D.Double(screenXY.getX(), screenXY.getY() - 15, selectedTextWrapper.getWidth(), selectedTextWrapper.getHeight()); if (screenRect.contains(e.getX(), e.getY())) { Point2D point = e.getPoint(); String inputText = textContentMap.get(selectedTextWrapper); if (inputText == null) { inputText = ""; } String[] lines = inputText.split("\n", 100); int cursorX = 0; int charCount = 0; int maxWidth = 0; int pickX = -1; FontMetrics fm = getGraphics().getFontMetrics(); for (int i = 0; i < lines.length; i++) { int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } if (maxWidth < 100) { maxWidth = 100; } Point2D screenPoint = ChartMaskingUtilities.translateChartPoint( new Point2D.Double(selectedTextWrapper.getX(), selectedTextWrapper.getY()), getScreenDataArea(), getChart()); if (point.getX() <= screenPoint.getX() + 11 + maxWidth && point.getY() <= screenPoint.getY() + lines.length * 15 - 15) { textInputPoint = screenPoint; textInputContent = inputText; textInputFlag = true; textContentMap.remove(selectedTextWrapper); selectedTextWrapper = null; textInputCursorIndex = 0; for (int i = 0; i < lines.length; i++) { if (point.getY() > screenPoint.getY() + i * 15 - 15 && point.getY() <= screenPoint.getY() + i * 15) { cursorX = fm.stringWidth(lines[i]); if (point.getX() >= screenPoint.getX() && point.getX() <= screenPoint.getX() + 3 + cursorX) { if (point.getX() >= screenPoint.getX() && point.getX() < screenPoint.getX() + 3) { pickX = 0; } double lastEnd = screenPoint.getX() + 3; for (int j = 0; j < lines[i].length(); j++) { int size = fm.stringWidth(lines[i].substring(0, j + 1)); double newEnd = screenPoint.getX() + 3 + size; if (point.getX() >= lastEnd && point.getX() < lastEnd + (newEnd - lastEnd) / 2) { pickX = j; } else if (point.getX() >= lastEnd + (newEnd - lastEnd) / 2 && point.getX() < newEnd) { pickX = j + 1; } lastEnd = newEnd; } if (pickX >= 0) { textInputCursorIndex = charCount + pickX; } } else { textInputCursorIndex = charCount + lines[i].length(); } break; } charCount += lines[i].length() + 1; } } } } selectText(e.getX(), e.getY()); if (selectedTextWrapper == null && !textInputFlag && newTextEnabled && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { textInputFlag = true; textInputPoint = e.getPoint(); } } else { Point2D point = e.getPoint(); boolean finishInput = false; // if (point.getX() < textInputPoint.getX() || point.getY() < textInputPoint.getY() - 15) { // finishInput = true; // } else { String inputText = textInputContent; if (inputText == null) { inputText = ""; } String[] lines = inputText.split("\n", 100); int cursorX = 0; int charCount = 0; int maxWidth = 0; int pickX = -1; FontMetrics fm = getGraphics().getFontMetrics(); for (int i = 0; i < lines.length; i++) { int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } if (maxWidth < 100) { maxWidth = 100; } if (point.getX() > textInputPoint.getX() + 11 + maxWidth || point.getY() > textInputPoint.getY() + lines.length * 15 - 15 || point.getX() < textInputPoint.getX() || point.getY() < textInputPoint.getY() - 15) { finishInput = true; } else { for (int i = 0; i < lines.length; i++) { if (point.getY() > textInputPoint.getY() + i * 15 - 15 && point.getY() <= textInputPoint.getY() + i * 15) { cursorX = fm.stringWidth(lines[i]); if (point.getX() >= textInputPoint.getX() && point.getX() <= textInputPoint.getX() + 3 + cursorX) { if (point.getX() >= textInputPoint.getX() && point.getX() < textInputPoint.getX() + 3) { pickX = 0; } double lastEnd = textInputPoint.getX() + 3; for (int j = 0; j < lines[i].length(); j++) { int size = fm.stringWidth(lines[i].substring(0, j + 1)); double newEnd = textInputPoint.getX() + 3 + size; if (point.getX() >= lastEnd && point.getX() < lastEnd + (newEnd - lastEnd) / 2) { pickX = j; } else if (point.getX() >= lastEnd + (newEnd - lastEnd) / 2 && point.getX() < newEnd) { pickX = j + 1; } lastEnd = newEnd; } if (pickX >= 0) { textInputCursorIndex = charCount + pickX; } } else { textInputCursorIndex = charCount + lines[i].length(); } break; } charCount += lines[i].length() + 1; } } // } if (finishInput) { if (textInputContent != null && textInputContent.length() > 0) { double xNew = ChartMaskingUtilities.translateScreenX(textInputPoint.getX(), getScreenDataArea(), getChart()); double yNew = ChartMaskingUtilities.translateScreenY(textInputPoint.getY(), getScreenDataArea(), getChart(), 0); textContentMap.put(new Rectangle2D.Double(xNew, yNew, maxWidth, lines.length * 15), textInputContent); } textInputContent = null; textInputCursorIndex = 0; textInputFlag = false; } } } }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void drawInformationBox(Graphics2D g2, Activities activities, Rectangle2D rect, List<String> params, List<String> values, String totalParam, double totalValue, Color background_color, Color border_color) { final Font oldFont = g2.getFont(); final Font paramFont = oldFont; final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont); final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1); final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont); final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1); final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont); final int x = (int) rect.getX(); final int y = (int) rect.getY(); final int width = (int) rect.getWidth(); final int height = (int) rect.getHeight(); final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Composite oldComposite = g2.getComposite(); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(border_color);//from ww w . ja v a 2 s . com g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15); g2.setColor(background_color); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect(x, y, width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); final Date date = activities.getDate().getTime(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy"); final String dateString = simpleDateFormat.format(date); final int padding = 5; int yy = y + padding + dateFontMetrics.getAscent(); g2.setFont(dateFont); g2.setColor(COLOR_BLUE); g2.drawString(dateString, ((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x, yy); int index = 0; final int dateInfoHeightMargin = 5; final int infoTotalHeightMargin = 5; final int paramValueHeightMargin = 0; yy += dateFontMetrics.getDescent() + dateInfoHeightMargin + Math.max(paramFontMetrics.getAscent(), valueFontMetrics.getAscent()); for (String param : params) { final String value = values.get(index++); g2.setColor(Color.BLACK); g2.setFont(paramFont); g2.drawString(param + ":", padding + x, yy); g2.setFont(valueFont); g2.drawString(value, width - padding - valueFontMetrics.stringWidth(value) + x, yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()); } if (values.size() > 1) { yy -= paramValueHeightMargin; yy += infoTotalHeightMargin; if (totalValue > 0.0) { g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR); } else if (totalValue < 0.0) { g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR); } g2.setFont(paramFont); g2.drawString(totalParam + ":", padding + x, yy); g2.setFont(valueFont); final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); final String totalValueStr = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalValue); g2.drawString(totalValueStr, width - padding - valueFontMetrics.stringWidth(totalValueStr) + x, yy); } g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:net.geoprism.dashboard.DashboardMap.java
private BufferedImage getLegendTitleImage(DashboardLayer layer) { FontMetrics fm; int textWidth; int textHeight; int textBoxHorizontalPadding = 4; int textBoxVerticalPadding = 4; int borderWidth = 2; int paddedTitleHeight; int paddedTitleWidth; int titleLeftPadding = textBoxHorizontalPadding; BufferedImage newLegendTitleBase; Graphics2D newLegendTitleBaseGraphic = null; try {//from w ww . j a v a 2 s . c o m // Build the Font object Font titleFont = new Font(layer.getName(), Font.BOLD, 14); // Build variables for base legend graphic construction try { newLegendTitleBase = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); newLegendTitleBaseGraphic = newLegendTitleBase.createGraphics(); newLegendTitleBaseGraphic.setFont(titleFont); fm = newLegendTitleBaseGraphic.getFontMetrics(); textHeight = fm.getHeight(); textWidth = fm.stringWidth(layer.getName()); paddedTitleWidth = textWidth + (textBoxHorizontalPadding * 2) + (borderWidth * 2); paddedTitleHeight = textHeight + (textBoxVerticalPadding * 2) + (borderWidth * 2); } finally { // dispose of temporary graphics context if (newLegendTitleBaseGraphic != null) { newLegendTitleBaseGraphic.dispose(); } } titleLeftPadding = ((paddedTitleWidth / 2) - ((textWidth + (textBoxHorizontalPadding * 2) + (borderWidth * 2)) / 2)) + textBoxHorizontalPadding; newLegendTitleBase = new BufferedImage(paddedTitleWidth, paddedTitleHeight, BufferedImage.TYPE_INT_ARGB); newLegendTitleBaseGraphic = newLegendTitleBase.createGraphics(); newLegendTitleBaseGraphic.drawImage(newLegendTitleBase, 0, 0, null); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); newLegendTitleBaseGraphic.setFont(titleFont); // draw title text fm = newLegendTitleBaseGraphic.getFontMetrics(); newLegendTitleBaseGraphic.setColor(Color.WHITE); newLegendTitleBaseGraphic.drawString(layer.getName(), titleLeftPadding, fm.getAscent() + textBoxVerticalPadding); newLegendTitleBaseGraphic.drawImage(newLegendTitleBase, 0, 0, null); } finally { if (newLegendTitleBaseGraphic != null) { newLegendTitleBaseGraphic.dispose(); } } return newLegendTitleBase; }
From source file:org.multibit.viewsystem.swing.view.panels.ShowPreferencesPanel.java
private JPanel createLanguagePanel(int stentWidth) { // Language radios. MultiBitTitledPanel languagePanel = new MultiBitTitledPanel( controller.getLocaliser().getString("showPreferencesPanel.languageTitle"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0;// w ww .j ava 2 s .c om constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.05; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; JPanel indent = MultiBitTitledPanel.getIndentPanel(1); languagePanel.add(indent, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 3; constraints.weightx = 0.3; constraints.weighty = 0.3; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; JPanel stent = MultiBitTitledPanel.createStent(stentWidth); languagePanel.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; languagePanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS), constraints); ButtonGroup languageUsageGroup = new ButtonGroup(); useDefaultLocale = new JRadioButton(controller.getLocaliser().getString("showPreferencesPanel.useDefault")); useDefaultLocale.setOpaque(false); useDefaultLocale.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); JRadioButton useSpecific = new JRadioButton( controller.getLocaliser().getString("showPreferencesPanel.useSpecific")); useSpecific.setOpaque(false); useSpecific.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); ItemListener itemListener = new ChangeLanguageUsageListener(); useDefaultLocale.addItemListener(itemListener); useSpecific.addItemListener(itemListener); languageUsageGroup.add(useDefaultLocale); languageUsageGroup.add(useSpecific); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 4; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; languagePanel.add(useDefaultLocale, constraints); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 1; constraints.gridy = 5; constraints.weightx = 0.2; constraints.weighty = 0.3; constraints.gridwidth = 3; constraints.anchor = GridBagConstraints.LINE_START; languagePanel.add(useSpecific, constraints); // Language combo box. int numberOfLanguages = Integer .parseInt(controller.getLocaliser().getString("showPreferencesPanel.numberOfLanguages")); // Languages are added to the combo box in alphabetic order. languageDataSet = new TreeSet<LanguageData>(); for (int i = 0; i < numberOfLanguages; i++) { String languageCode = controller.getLocaliser() .getString("showPreferencesPanel.languageCode." + (i + 1)); String language = controller.getLocaliser().getString("showPreferencesPanel.language." + (i + 1)); LanguageData languageData = new LanguageData(); languageData.languageCode = languageCode; languageData.language = language; languageData.image = createImageIcon(languageCode); languageData.image.setDescription(language); languageDataSet.add(languageData); } Integer[] indexArray = new Integer[languageDataSet.size()]; int index = 0; for (@SuppressWarnings("unused") LanguageData languageData : languageDataSet) { indexArray[index] = index; index++; } languageComboBox = new JComboBox(indexArray); languageComboBox.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); languageComboBox.setOpaque(false); LanguageComboBoxRenderer renderer = new LanguageComboBoxRenderer(); FontMetrics fontMetrics = getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()); Dimension preferredSize = new Dimension(fontMetrics.stringWidth(A_LONG_LANGUAGE_NAME) + LANGUAGE_COMBO_WIDTH_DELTA + LANGUAGE_CODE_IMAGE_WIDTH, fontMetrics.getHeight() + COMBO_HEIGHT_DELTA); renderer.setPreferredSize(preferredSize); languageComboBox.setRenderer(renderer); // Get the languageCode value stored in the model. String userLanguageCode = controller.getModel().getUserPreference(CoreModel.USER_LANGUAGE_CODE); if (userLanguageCode == null || CoreModel.USER_LANGUAGE_IS_DEFAULT.equals(userLanguageCode)) { useDefaultLocale.setSelected(true); languageComboBox.setEnabled(false); } else { useSpecific.setSelected(true); int startingIndex = 0; Integer languageCodeIndex = 0; for (LanguageData languageData : languageDataSet) { if (languageData.languageCode.equals(userLanguageCode)) { languageCodeIndex = startingIndex; break; } startingIndex++; } if (languageCodeIndex != 0) { languageComboBox.setSelectedItem(languageCodeIndex); languageComboBox.setEnabled(true); } } // Store original value for use by submit action. originalUserLanguageCode = userLanguageCode; constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 6; constraints.weightx = 0.8; constraints.weighty = 0.6; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_START; languagePanel.add(languageComboBox, constraints); JPanel fill1 = new JPanel(); fill1.setOpaque(false); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 4; constraints.gridy = 6; constraints.weightx = 20; constraints.weighty = 1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; languagePanel.add(fill1, constraints); return languagePanel; }