List of usage examples for java.awt FontMetrics getHeight
public int getHeight()
From source file:edu.ku.brc.ui.UIRegistry.java
/** * Writes a string message into the BufferedImage on GlassPane and sets the main component's visibility to false and * shows the GlassPane./*w w w .ja v a 2 s . c o m*/ * @param msg the message * @param pointSize the Font point size for the message to be writen in */ public static GhostGlassPane writeGlassPaneMsg(final String msg, final int pointSize) { GhostGlassPane glassPane = getGlassPane(); if (glassPane != null) { glassPane.finishDnD(); } glassPane.setMaskingEvents(true); Component mainComp = get(MAINPANE); if (mainComp != null && glassPane != null) { JFrame frame = (JFrame) get(FRAME); frameRect = frame.getBounds(); int y = 0; JMenuBar menuBar = null; Dimension size = mainComp.getSize(); if (UIHelper.getOSType() != UIHelper.OSTYPE.MacOSX) { menuBar = frame.getJMenuBar(); size.height += menuBar.getSize().height; y += menuBar.getSize().height; } BufferedImage buffer = getGlassPaneBufferedImage(size.width, size.height); Graphics2D g2 = buffer.createGraphics(); if (menuBar != null) { menuBar.paint(g2); } g2.translate(0, y); mainComp.paint(g2); g2.translate(0, -y); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(new Color(255, 255, 255, 128)); g2.fillRect(0, 0, size.width, size.height); g2.setFont(new Font((new JLabel()).getFont().getName(), Font.BOLD, pointSize)); FontMetrics fm = g2.getFontMetrics(); int tw = fm.stringWidth(msg); int th = fm.getHeight(); int tx = (size.width - tw) / 2; int ty = (size.height - th) / 2; int expand = 20; int arc = expand * 2; g2.setColor(Color.WHITE); g2.fillRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc, arc); g2.setColor(Color.DARK_GRAY); g2.drawRoundRect(tx - (expand / 2), ty - fm.getAscent() - (expand / 2), tw + expand, th + expand, arc, arc); g2.setColor(Color.BLACK); g2.drawString(msg, tx, ty); g2.dispose(); glassPane.setImage(buffer); glassPane.setPoint(new Point(0, 0), GhostGlassPane.ImagePaintMode.ABSOLUTE); glassPane.setOffset(new Point(0, 0)); glassPane.setVisible(true); mainComp.setVisible(false); //Using paintImmediately fixes problems with glass pane not showing, such as for workbench saves initialed //during workbench or app shutdown. Don't know if there is a better way to fix it. //glassPane.repaint(); glassPane.paintImmediately(glassPane.getBounds()); showingGlassPane = true; } return glassPane; }
From source file:edu.ku.brc.services.mapping.LocalityMapper.java
/** * Grabs a new map from the web service and appropriately adorns it * with labels and markers./*from ww w.ja va2 s . co m*/ * * @return a map image as an icon * @throws HttpException a network error occurred while grabbing the map from the service * @throws IOException a network error occurred while grabbing the map from the service */ protected Icon grabNewMap() throws HttpException, IOException { recalculateBoundingBox(); if (!cacheValid) { // Image mapImage = getMapFromService("mapus.jpl.nasa.gov", // "/wms.cgi?request=GetMap&srs=EPSG:4326&format=image/png&styles=visual", // "global_mosaic", // mapMinLat, mapMinLong, mapMaxLat, mapMaxLong, maxMapHeight, maxMapWidth); // // Image overlayImage = getMapFromService("129.237.201.132", // "/cgi-bin/mapserv?map=/var/www/maps/specify.map&service=WMS&request=GetMap&srs=EPSG:4326&version=1.3.1&format=image/png&transparent=true", // "states,rivers", // mapMinLat, mapMinLong, mapMaxLat, mapMaxLong, maxMapHeight, maxMapWidth); Image mapImage = getMapFromService("lifemapper.org", //$NON-NLS-1$ "/ogc?map=specify.map&service=WMS&request=GetMap&srs=EPSG:4326&version=1.3.1&STYLES=&format=image/png&transparent=TRUE", //$NON-NLS-1$ "global_mosaic,states,rivers", //$NON-NLS-1$ mapMinLat, mapMinLong, mapMaxLat, mapMaxLong, maxMapHeight, maxMapWidth); mapIcon = new ImageIcon(mapImage); // overlayIcon = new ImageIcon(overlayImage); cacheValid = true; mapWidth = mapIcon.getIconWidth(); mapHeight = mapIcon.getIconHeight(); if (mapWidth < 0 || mapHeight < 0) { throw new IOException("Request for map failed. Received map has negative width or height."); //$NON-NLS-1$ } mapLatRange = mapMaxLat - mapMinLat; mapLongRange = mapMaxLong - mapMinLong; pixelPerLatRatio = mapHeight / mapLatRange; pixelPerLongRatio = mapWidth / mapLongRange; for (int i = 0; i < mapLocations.size(); ++i) { MapLocationIFace loc = mapLocations.get(i); Point iconLoc = determinePixelCoordsOfMapLocationIFace(loc); markerLocations.set(i, iconLoc); } cacheValid = true; } Icon icon = new Icon() { public void paintIcon(Component c, Graphics g, int x, int y) { // this helps keep the labels inside the map g.setClip(x, y, mapWidth, mapHeight); // log the x and y for the MouseMotionListener mostRecentPaintedX = x; mostRecentPaintedY = y; Point currentLocPoint = null; if (currentLoc != null) { currentLocPoint = determinePixelCoordsOfMapLocationIFace(currentLoc); } mapIcon.paintIcon(c, g, x, y); // overlayIcon.paintIcon(c, g, x, y); Point lastLoc = null; for (int i = 0; i < mapLocations.size(); ++i) { Point markerLoc = markerLocations.get(i); String label = labels.get(i); boolean current = (currentLoc != null) && markerLoc.equals(currentLocPoint); if (markerLoc == null) { log.error("A marker location is null"); //$NON-NLS-1$ continue; } if (!pointIsOnMapIcon(x + markerLoc.x, y + markerLoc.y)) { log.error("A marker location is off the map"); //$NON-NLS-1$ continue; } if (showArrows && lastLoc != null) { int x1 = x + lastLoc.x; int y1 = y + lastLoc.y; int x2 = x + markerLoc.x; int y2 = y + markerLoc.y; Color origColor = g.getColor(); if (current && !animationInProgress) { g.setColor(getCurrentLocColor()); } else { g.setColor(arrowColor); } GraphicsUtils.drawArrow(g, x1, y1, x2, y2, 2, 2); g.setColor(origColor); } if (current) { currentLocMarker.paintIcon(c, g, markerLoc.x + x, markerLoc.y + y); } else { marker.paintIcon(c, g, markerLoc.x + x, markerLoc.y + y); } if (label != null) { Color origColor = g.getColor(); FontMetrics fm = g.getFontMetrics(); int length = fm.stringWidth(label); g.setColor(Color.WHITE); g.fillRect(markerLoc.x + x - (length / 2), markerLoc.y + y - (fm.getHeight() / 2), length, fm.getHeight()); g.setColor(labelColor); GraphicsUtils.drawCenteredString(label, g, markerLoc.x + x, markerLoc.y + y); g.setColor(origColor); } lastLoc = markerLoc; } if (showArrowAnimations && animationInProgress) { int startIndex = mapLocations.indexOf(animStartLoc); int endIndex = mapLocations.indexOf(animEndLoc); if (startIndex != -1 && endIndex != -1) { Point startPoint = markerLocations.get(startIndex); Point endPoint = markerLocations.get(endIndex); Point arrowEnd = GraphicsUtils.getPointAlongLine(startPoint, endPoint, percent); Color orig = g.getColor(); g.setColor(getCurrentLocColor()); GraphicsUtils.drawArrow(g, startPoint.x + x, startPoint.y + y, arrowEnd.x + x, arrowEnd.y + y, 5, 3); g.setColor(orig); } } } public int getIconWidth() { return mapWidth; } public int getIconHeight() { return mapHeight; } }; return icon; }
From source file:edu.ku.brc.ui.tmanfe.SpreadSheet.java
/** * //from w ww.java 2s . c o m */ 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:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java
private byte[] generateNoDataChart(int width, int height) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(parseColor(statsManager.getChartBackgroundColor())); g2d.clearRect(0, 0, width - 1, height - 1); g2d.setColor(parseColor("#cccccc")); g2d.drawRect(0, 0, width - 1, height - 1); Font f = new Font("SansSerif", Font.PLAIN, 12); g2d.setFont(f);//from ww w .j a va 2s . com FontMetrics fm = g2d.getFontMetrics(f); String noData = msgs.getString("no_data"); int noDataWidth = fm.stringWidth(noData); int noDataHeight = fm.getHeight(); g2d.setColor(parseColor("#555555")); g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { log.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void drawBusyBox(Graphics2D g2, JXLayer<? extends V> layer) { final Font oldFont = g2.getFont(); final Font font = oldFont; final FontMetrics fontMetrics = g2.getFontMetrics(font); // Not sure why. Draw GIF image on JXLayer, will cause endless setDirty // being triggered by system. //final Image image = ((ImageIcon)Icons.BUSY).getImage(); //final int imgWidth = Icons.BUSY.getIconWidth(); //final int imgHeight = Icons.BUSY.getIconHeight(); //final int imgMessageWidthMargin = 5; final int imgWidth = 0; final int imgHeight = 0; final int imgMessageWidthMargin = 0; final String message = MessagesBundle.getString("info_message_retrieving_latest_stock_price"); final int maxWidth = imgWidth + imgMessageWidthMargin + fontMetrics.stringWidth(message); final int maxHeight = Math.max(imgHeight, fontMetrics.getHeight()); final int padding = 5; final int width = maxWidth + (padding << 1); final int height = maxHeight + (padding << 1); final int x = (int) this.drawArea.getX() + (((int) this.drawArea.getWidth() - width) >> 1); final int y = (int) this.drawArea.getY() + (((int) this.drawArea.getHeight() - height) >> 1); final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Composite oldComposite = g2.getComposite(); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(COLOR_BORDER);/*from w ww .j ava2 s .c o m*/ g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15); g2.setColor(COLOR_BACKGROUND); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect(x, y, width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); //g2.drawImage(image, x + padding, y + ((height - imgHeight) >> 1), layer.getView()); g2.setFont(font); g2.setColor(COLOR_BLUE); int yy = y + ((height - fontMetrics.getHeight()) >> 1) + fontMetrics.getAscent(); g2.setFont(font); g2.setColor(COLOR_BLUE); g2.drawString(message, x + padding + imgWidth + imgMessageWidthMargin, yy); g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:org.executequery.gui.erd.ErdTable.java
/** <p>Initialises the state of this instance. */ private void jbInit() throws Exception { Font tableNameFont = parent.getTableNameFont(); Font columnNameFont = parent.getColumnNameFont(); FontMetrics fmColumns = getFontMetrics(columnNameFont); FontMetrics fmTitle = getFontMetrics(tableNameFont); if (columns != null) { for (int i = 0; i < columns.length; i++) { ColumnData column = columns[i]; int valueWidth = fmColumns.stringWidth(column.getColumnName()); dataTypeOffset = Math.max(dataTypeOffset, valueWidth); valueWidth = fmColumns.stringWidth(column.getFormattedDataType()); keyLabelOffset = Math.max(keyLabelOffset, valueWidth); }// w w w . j a v a2s .co m } // add a further offset to the data type and key label offsets dataTypeOffset += 10; keyLabelOffset += 2; int keyWidth = fmColumns.stringWidth(PRIMARY + FOREIGN); int maxWordLength = dataTypeOffset + keyLabelOffset + keyWidth + 10; // compare to the title length maxWordLength = Math.max(fmTitle.stringWidth(tableName), maxWordLength); // add 20px to the final width FINAL_WIDTH = maxWordLength;// + 20; if (ArrayUtils.isEmpty(columns)) { FINAL_WIDTH += 80; } // minimum width is 130px // if (FINAL_WIDTH < 130) // FINAL_WIDTH = 130; TITLE_BAR_HEIGHT = fmTitle.getHeight() + 5; int keysCount = 0; for (int i = 0; i < columns.length; i++) { if (columns[i].isKey()) { keysCount++; } } if (columns.length > 0) { if (displayReferencedKeysOnly) { if (keysCount > 0) { FINAL_HEIGHT = (fmColumns.getHeight() * keysCount) + TITLE_BAR_HEIGHT + 10; } else { FINAL_HEIGHT = fmColumns.getHeight() + TITLE_BAR_HEIGHT + 8; } } else { FINAL_HEIGHT = (fmColumns.getHeight() * columns.length) + TITLE_BAR_HEIGHT + 10; } } else { // have one blank row (column) on the table FINAL_HEIGHT = fmColumns.getHeight() + TITLE_BAR_HEIGHT + 10; } int joinSpacing = 10; int vertSize = (FINAL_HEIGHT / joinSpacing) - 1; int horizSize = (FINAL_WIDTH / joinSpacing) - 1; verticalLeftJoins = new ErdTableConnectionPoint[vertSize]; verticalRightJoins = new ErdTableConnectionPoint[vertSize]; horizontalTopJoins = new ErdTableConnectionPoint[horizSize]; horizontalBottomJoins = new ErdTableConnectionPoint[horizSize]; int midPointVert = FINAL_HEIGHT / 2; int midPointHoriz = FINAL_WIDTH / 2; int aboveMidPoint = midPointHoriz; int belowMidPoint = midPointHoriz; for (int i = 0; i < horizontalTopJoins.length; i++) { horizontalTopJoins[i] = new ErdTableConnectionPoint(TOP_JOIN); horizontalBottomJoins[i] = new ErdTableConnectionPoint(BOTTOM_JOIN); if (i == 0) { horizontalTopJoins[i].setPosition(midPointHoriz); horizontalBottomJoins[i].setPosition(midPointHoriz); } else if (i % 2 == 0) { belowMidPoint -= joinSpacing; if (belowMidPoint > 10) { horizontalTopJoins[i].setPosition(belowMidPoint); horizontalBottomJoins[i].setPosition(belowMidPoint); } } else { aboveMidPoint += joinSpacing; if (aboveMidPoint < FINAL_WIDTH - 10) { horizontalTopJoins[i].setPosition(belowMidPoint); horizontalBottomJoins[i].setPosition(belowMidPoint); } horizontalTopJoins[i].setPosition(aboveMidPoint); horizontalBottomJoins[i].setPosition(aboveMidPoint); } } aboveMidPoint = midPointVert; belowMidPoint = midPointVert; for (int i = 0; i < verticalLeftJoins.length; i++) { verticalLeftJoins[i] = new ErdTableConnectionPoint(LEFT_JOIN); verticalRightJoins[i] = new ErdTableConnectionPoint(RIGHT_JOIN); if (i == 0) { verticalLeftJoins[i].setPosition(midPointVert); verticalRightJoins[i].setPosition(midPointVert); } else if (i % 2 == 0) { belowMidPoint -= joinSpacing; if (belowMidPoint < FINAL_HEIGHT - 10) { verticalLeftJoins[i].setPosition(belowMidPoint); verticalRightJoins[i].setPosition(belowMidPoint); } } else { aboveMidPoint += joinSpacing; if (aboveMidPoint > 10) { verticalLeftJoins[i].setPosition(aboveMidPoint); verticalRightJoins[i].setPosition(aboveMidPoint); } } } SwingUtilities.invokeLater(new Runnable() { public void run() { originalData = new ColumnData[columns.length]; for (int i = 0; i < columns.length; i++) { originalData[i] = new ColumnData(); originalData[i].setValues(columns[i]); } } }); }
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 {//w w w . j a v a2s . co 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:ded.ui.DiagramController.java
/** Check to see if the font is rendering properly. I have had a * lot of trouble getting this to work on a wide range of * machines and JVMs. If the font rendering does not work, just * alert the user to the problem but keep going. */ public void checkFontRendering() { // Render the glyph for 'A' in a box just large enough to // contain it when rendered properly. int width = 9; int height = 11; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); ColorModel colorModel = bi.getColorModel(); g.setColor(Color.WHITE);/* www . j a v a2s . co m*/ g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); g.setFont(this.dedWindow.diagramFont); g.drawString("A", 0, 10); // Print that glyph as a string. StringBuilder sb = new StringBuilder(); for (int y = 0; y < height; y++) { int bits = 0; for (int x = 0; x < width; x++) { int pixel = bi.getRGB(x, y); int red = colorModel.getRed(pixel); int green = colorModel.getGreen(pixel); int blue = colorModel.getBlue(pixel); int alpha = colorModel.getAlpha(pixel); boolean isWhite = (red == 255 && green == 255 && blue == 255 && alpha == 255); boolean isBlack = (red == 0 && green == 0 && blue == 0 && alpha == 255); sb.append( isWhite ? "_" : isBlack ? "X" : ("(" + red + "," + green + "," + blue + "," + alpha + ")")); bits <<= 1; if (!isWhite) { bits |= 1; } } sb.append(String.format(" (0x%03X)\n", bits)); } // Also include some of the font metrics. FontMetrics fm = g.getFontMetrics(); sb.append("fm: ascent=" + fm.getAscent() + " leading=" + fm.getLeading() + " charWidth('A')=" + fm.charWidth('A') + " descent=" + fm.getDescent() + " height=" + fm.getHeight() + "\n"); String actualGlyph = sb.toString(); g.dispose(); // The expected glyph and metrics. String expectedGlyph = "_________ (0x000)\n" + "____X____ (0x010)\n" + "___X_X___ (0x028)\n" + "___X_X___ (0x028)\n" + "__X___X__ (0x044)\n" + "__X___X__ (0x044)\n" + "__XXXXX__ (0x07C)\n" + "_X_____X_ (0x082)\n" + "_X_____X_ (0x082)\n" + "_X_____X_ (0x082)\n" + "_________ (0x000)\n" + "fm: ascent=10 leading=1 charWidth('A')=9 descent=3 height=14\n"; if (!expectedGlyph.equals(actualGlyph)) { // Currently, this is known to happen when using OpenJDK 6 // and 7, with 6 being close to right and 7 being very bad. // I also have reports of it happening on certain Mac OS/X // systems, but I haven't been able to determine what the // important factor there is. String warningMessage = "There is a problem with the font rendering. The glyph " + "for the letter 'A' should look like:\n" + expectedGlyph + "but it renders as:\n" + actualGlyph + "\n" + "This probably means there is a bug in the TrueType " + "font library. You might try a different Java version. " + "(I'm working on how to solve this permanently.)"; System.err.println(warningMessage); this.log(warningMessage); SwingUtil.errorMessageBox(null /*component*/, warningMessage); } }
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;//from w w w. j ava2 s .co m } 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: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;//from ww w. j a v a 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; }