public static String getClippedText(String text, FontMetrics fm, int maxWidth) { if ((text == null) || (text.length() == 0)) { return ""; } int width = SwingUtilities.computeStringWidth(fm, text); if (width > maxWidth) { int totalWidth = SwingUtilities.computeStringWidth(fm, ELLIPSIS); for (int i = 0; i < text.length(); i++) { totalWidth += fm.charWidth(text.charAt(i)); if (totalWidth > maxWidth) { return text.substring(0, i) + ELLIPSIS; } } } return text; }
private void drawColumn( Graphics g, State state, EcoIdentity onGround, int x, int y, int cubeSize) { String label; int strWidth; EcoState ecoState; EcoIdentity entity = onGround; int yy = y - cubeSize; int strHeight = g.getFontMetrics().getHeight() / 2; Color backColor, frontColor; while (entity != null) { ecoState = state.ecoStates.get(entity); if (ecoState == null) { backColor = Color.DARK_GRAY; frontColor = Color.WHITE; } else { switch (ecoState) { case ESCAPING: backColor = Color.RED; frontColor = Color.BLACK; break; case ESCAPED: backColor = Color.PINK; frontColor = Color.BLACK; break; case SATISFACTING: backColor = Color.WHITE; frontColor = Color.BLACK; break; case SATISFACTED: backColor = Color.GREEN; frontColor = Color.BLACK; break; case INITIALIZED: case INITIALIZING: default: backColor = Color.DARK_GRAY; frontColor = Color.WHITE; break; } } g.setColor(backColor); g.fillRect(x, yy, cubeSize, cubeSize); g.setColor(frontColor); g.drawRect(x, yy, cubeSize, cubeSize); label = entity.toString(); strWidth = SwingUtilities.computeStringWidth(g.getFontMetrics(), label); g.drawString(label, x + (cubeSize - strWidth) / 2, yy + (cubeSize - strHeight) / 2); yy -= cubeSize; entity = state.map.get(entity); } }
// offset time interval labels, so they do not overlap previous & current slot nodes private int getXOffset() { if (isFirstSlot) { return 0; } else { return SwingUtilities.computeStringWidth( view.getFontMetrics(), startTimeIntervalDomain.toString()) / 2; } } // end getXOffset
@Override protected void paintTitle(Graphics2D g2) { FontMetrics fm = g2.getFontMetrics(); int titleWidth = SwingUtilities.computeStringWidth(fm, title); g2.setColor(Color.WHITE); Rectangle r = g2.getClipBounds(); int textX = (r.width - titleWidth) / 2; int textY = ((r.height) / 2) - ((fm.getAscent() + fm.getDescent()) / 2) + fm.getAscent(); g2.drawString(title, textX + 1, textY + 1); g2.setColor(Color.BLACK); g2.drawString(title, textX, textY); }
private PathButton(final String item) { super(item); setFont(pathFont); setFocusable(false); setBorderPainted(false); setContentAreaFilled(false); setFocusPainted(false); setMargin(new Insets(0, 0, 0, 0)); FontMetrics metrics = getFontMetrics(pathFont); textWidth = SwingUtilities.computeStringWidth(metrics, getText()); double rads = Math.toRadians(pathShadowDirection); shadowOffsetX = (float) Math.cos(rads) * pathShadowDistance; shadowOffsetY = (float) Math.sin(rads) * pathShadowDistance; addMouseListener(eventHandler); addMouseListener(new HiglightHandler()); }
/** * Computes the maximum width of a label in the configuration form. * * @param configForm the configuration form containing all labels. * @return the maximum width of a label in the configuration form */ private int computeLabelWidth(ChatRoomConfigurationForm configForm) { int labelWidth = 0; Iterator<ChatRoomConfigurationFormField> configurationSet = configForm.getConfigurationSet(); while (configurationSet.hasNext()) { ChatRoomConfigurationFormField formField = configurationSet.next(); if (formField.getLabel() == null) continue; JLabel label = new JLabel(formField.getLabel()); int newLabelWidth = SwingUtilities.computeStringWidth( label.getFontMetrics(label.getFont()), formField.getLabel()); if (newLabelWidth > labelWidth) labelWidth = newLabelWidth; } // We add 10 pixels to be sure that even after adding the ':' char // the label will rest visible. return labelWidth + 10; }
public boolean paint(Graphics graphics) { if (!Game.isLoggedIn()) return false; try { Graphics2D g = (Graphics2D) graphics; PComponent clayout = null; try { clayout = new PColumnLayout( 227, 404, infoColumnValues, infoColumnData, new Font("Arial", 0, 9), PColumnLayout.ColorScheme.WHITE); } catch (Exception e) { e.printStackTrace(); } getFrame("options").removeComponent(firstLayout); getFrame("options").removeComponent(secondLayout); int secondColx = -1; int bestLength = -1; firstColumn.clear(); secondColumn.clear(); if (checkBoxes.size() <= 6) firstColumn.putAll(checkBoxes); else { for (int i = 0; i < checkBoxes.size(); i++) { if (i <= 5) { String text; Iterator it = checkBoxes.keySet().iterator(); for (int j = 0; j < i; j++) it.next(); text = (String) it.next(); int length = SwingUtilities.computeStringWidth(g.getFontMetrics(g.getFont()), text); if (length > bestLength) bestLength = length; firstColumn.put(text, checkBoxes.get(text)); } else { String text; Iterator it = checkBoxes.keySet().iterator(); for (int j = 0; j < i; j++) it.next(); text = (String) it.next(); secondColumn.put(text, checkBoxes.get(text)); } } } secondColx = 8 + bestLength; firstLayout = new PCheckBoxLayout( 8, 407, firstColumn .keySet() .toArray(new String[(firstColumn.size() > 6) ? 6 : firstColumn.size()]), firstColumn .values() .toArray(new PCheckBox[(firstColumn.size() > 6) ? 6 : firstColumn.size()]), new Font("Arial", 0, 11), PCheckBoxLayout.ColorScheme.WHITE); secondLayout = new PCheckBoxLayout( secondColx + 12, 407, secondColumn .keySet() .toArray(new String[(secondColumn.size() > 6) ? 6 : secondColumn.size()]), secondColumn .values() .toArray(new PCheckBox[(secondColumn.size() > 6) ? 6 : secondColumn.size()]), new Font("Arial", 0, 11), PCheckBoxLayout.ColorScheme.WHITE); getFrame("options").addComponent(firstLayout); getFrame("options").addComponent(secondLayout); if (showPaint) { Paint p = g.getPaint(); g.setPaint( new GradientPaint( 0, 1000, new Color(55, 55, 55, 240), 512, 472, new Color(15, 15, 15, 240))); g.fillRect(7, 396, 505, 128); final Point loc = Mouse.getLocation(); if (Mouse.isPressed()) { g.fillOval(loc.x - 5, loc.y - 5, 10, 10); g.drawOval(loc.x - 5, loc.y - 5, 10, 10); } g.drawLine(0, loc.y + 1, 766, loc.y + 1); g.drawLine(0, loc.y - 1, 766, loc.y - 1); g.drawLine(loc.x + 1, 0, loc.x + 1, 505); g.drawLine(loc.x - 1, 0, loc.x - 1, 505); g.setPaint(p); } if (clayout != null) getFrame("info").addComponent(clayout); PaintController.onRepaint(graphics); if (clayout != null) getFrame("info").removeComponent(clayout); if (!showPaint) return false; String infoTxt = name + " - " + "v" + version; g.drawString( infoTxt, 510 - SwingUtilities.computeStringWidth(g.getFontMetrics(g.getFont()), infoTxt), 468); int offset = 0; for (Skill skill : skills) { if (skill.xpGained() > 0) { PSkill skillComp = new PSkill(8, 397 + offset, skill.getSkill(), PSkill.ColorScheme.GRAPHITE); if (!getFrame("info").containsComponent(skillComp)) { getFrame("info").addComponent(skillComp); } offset += 20; } } // == Mouse == if (Mouse.isPressed()) { g.setColor(new Color(255, 252, 0, 150)); g.setColor(new Color(255, 252, 0, 100)); } else { g.setColor(new Color(255, 252, 0, 50)); } g.setColor(new Color(0, 0, 0, 50)); // == End mouse == } catch (Exception ignored) { // if (Utils.isDevMode()) // ignored.printStackTrace(); } return true; }
public static Dimension computeMultiLineDimension(FontMetrics fm, String[] strs) { int i, c, width = 0; for (i = 0, c = strs.length; i < c; i++) width = Math.max(width, SwingUtilities.computeStringWidth(fm, strs[i])); return new Dimension(width, fm.getHeight() * strs.length); }
/** * Compute and return the location of the icons origin, the location of origin of the text * baseline, and a possibly clipped version of the compound labels string. Locations are computed * relative to the viewR rectangle. This layoutCompoundLabel() does not know how to handle * LEADING/TRAILING values in horizontalTextPosition (they will default to RIGHT) and in * horizontalAlignment (they will default to CENTER). Use the other version of * layoutCompoundLabel() instead. */ public static String layoutCompoundLabel( FontMetrics fm, String[] text, Icon icon, int verticalAlignment, int horizontalAlignment, int verticalTextPosition, int horizontalTextPosition, Rectangle viewR, Rectangle iconR, Rectangle textR, int textIconGap) { /* Initialize the icon bounds rectangle iconR. */ if (icon != null) { iconR.width = icon.getIconWidth(); iconR.height = icon.getIconHeight(); } else { iconR.width = iconR.height = 0; } /* Initialize the text bounds rectangle textR. If a null * or and empty String was specified we substitute "" here * and use 0,0,0,0 for textR. */ // Fix for textIsEmpty sent by Paulo Santos boolean textIsEmpty = (text == null) || (text.length == 0) || (text.length == 1 && ((text[0] == null) || text[0].equals(""))); String rettext = ""; if (textIsEmpty) { textR.width = textR.height = 0; } else { Dimension dim = computeMultiLineDimension(fm, text); textR.width = dim.width; textR.height = dim.height; } /* Unless both text and icon are non-null, we effectively ignore * the value of textIconGap. The code that follows uses the * value of gap instead of textIconGap. */ int gap = (textIsEmpty || (icon == null)) ? 0 : textIconGap; if (!textIsEmpty) { /* If the label text string is too wide to fit within the available * space "..." and as many characters as will fit will be * displayed instead. */ int availTextWidth; if (horizontalTextPosition == CENTER) { availTextWidth = viewR.width; } else { availTextWidth = viewR.width - (iconR.width + gap); } if (textR.width > availTextWidth && text.length == 1) { String clipString = "..."; int totalWidth = SwingUtilities.computeStringWidth(fm, clipString); int nChars; for (nChars = 0; nChars < text[0].length(); nChars++) { totalWidth += fm.charWidth(text[0].charAt(nChars)); if (totalWidth > availTextWidth) { break; } } rettext = text[0].substring(0, nChars) + clipString; textR.width = SwingUtilities.computeStringWidth(fm, rettext); } } /* Compute textR.x,y given the verticalTextPosition and * horizontalTextPosition properties */ if (verticalTextPosition == TOP) { if (horizontalTextPosition != CENTER) { textR.y = 0; } else { textR.y = -(textR.height + gap); } } else if (verticalTextPosition == CENTER) { textR.y = (iconR.height / 2) - (textR.height / 2); } else { // (verticalTextPosition == BOTTOM) if (horizontalTextPosition != CENTER) { textR.y = iconR.height - textR.height; } else { textR.y = (iconR.height + gap); } } if (horizontalTextPosition == LEFT) { textR.x = -(textR.width + gap); } else if (horizontalTextPosition == CENTER) { textR.x = (iconR.width / 2) - (textR.width / 2); } else { // (horizontalTextPosition == RIGHT) textR.x = (iconR.width + gap); } /* labelR is the rectangle that contains iconR and textR. * Move it to its proper position given the labelAlignment * properties. * * To avoid actually allocating a Rectangle, Rectangle.union * has been inlined below. */ int labelR_x = Math.min(iconR.x, textR.x); int labelR_width = Math.max(iconR.x + iconR.width, textR.x + textR.width) - labelR_x; int labelR_y = Math.min(iconR.y, textR.y); int labelR_height = Math.max(iconR.y + iconR.height, textR.y + textR.height) - labelR_y; int dx, dy; if (verticalAlignment == TOP) { dy = viewR.y - labelR_y; } else if (verticalAlignment == CENTER) { dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height / 2)); } else { // (verticalAlignment == BOTTOM) dy = (viewR.y + viewR.height) - (labelR_y + labelR_height); } if (horizontalAlignment == LEFT) { dx = viewR.x - labelR_x; } else if (horizontalAlignment == RIGHT) { dx = (viewR.x + viewR.width) - (labelR_x + labelR_width); } else { // (horizontalAlignment == CENTER) dx = (viewR.x + (viewR.width / 2)) - (labelR_x + (labelR_width / 2)); } /* Translate textR and glypyR by dx,dy. */ textR.x += dx; textR.y += dy; iconR.x += dx; iconR.y += dy; return rettext; }
@Override protected void paintText( Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { g.setFont(font); int titleWidth = SwingUtilities.computeStringWidth(metrics, title); int preferredWidth = 0; if (isOneActionButtonEnabled()) { preferredWidth = calculateTabWidth(tabPlacement, tabIndex, metrics) - WIDTHDELTA - 15; if (isCloseEnabled()) preferredWidth -= BUTTONSIZE; if (isMaxEnabled()) preferredWidth -= BUTTONSIZE; } else { preferredWidth = titleWidth; } while (titleWidth > preferredWidth) { if (title.endsWith("...")) title = title.substring(0, title.indexOf("...") - 1).concat("..."); else title = title.substring(0, title.length() - 4).concat("..."); titleWidth = SwingUtilities.computeStringWidth(metrics, title); } textRect.width = titleWidth; View v = getTextViewForTab(tabIndex); if (v != null) { // html v.paint(g, textRect); } else { // plain text int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex); if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) { if (isSelected) g.setColor(TAB_SELECTED_FOREGROUND_COLOR); else { if (this.isTabHighlighted(tabIndex)) { g.setColor(TAB_HIGHLIGHT_FOREGROUND_COLOR); } else g.setColor(tabPane.getForegroundAt(tabIndex)); } BasicGraphicsUtils.drawString( g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); } else { // tab disabled g.setColor(tabPane.getBackgroundAt(tabIndex).brighter()); BasicGraphicsUtils.drawStringUnderlineCharAt( g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); g.setColor(tabPane.getBackgroundAt(tabIndex).darker()); BasicGraphicsUtils.drawStringUnderlineCharAt( g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1); } } }
@Override public Component getTreeCellRendererComponent( JTree tree, Object oValue, boolean bSelected, boolean bExpanded, boolean bLeaf, int iRow, boolean bHasFocus) { final JLabel lbl = (JLabel) super.getTreeCellRendererComponent( tree, oValue, bSelected, bExpanded, bLeaf, iRow, bHasFocus); String tmp = lbl.getText(); final List<PaintImage> images = new LinkedList<PaintImage>(); int idx = -1; int spaceX = SwingUtilities.computeStringWidth(lbl.getFontMetrics(lbl.getFont()), " "); while ((idx = tmp.indexOf("[$" + CollectableFieldFormat.class.getName() + ",")) != -1) { int formatEnd = tmp.indexOf("$]"); String format = tmp.substring(idx, formatEnd); String[] formatDef = format.split(","); try { CollectableFieldFormat clctformat = CollectableFieldFormat.getInstance(Class.forName(formatDef[1])); int x = SwingUtilities.computeStringWidth( lbl.getFontMetrics(lbl.getFont()), tmp.substring(0, idx)); NuclosImage img = (NuclosImage) clctformat.parse(null, formatDef[3]); String tmp1 = tmp.substring(0, idx); for (int i = 0; i < img.getWidth() / spaceX; i++) { tmp1 += " "; } tmp1 += tmp.substring(formatEnd + 2); tmp = tmp1; images.add(new PaintImage(x, img)); } catch (CollectableFieldFormatException e) { LOG.error("format exception at " + formatDef[1], e); } catch (ClassNotFoundException e) { LOG.error("class not found for " + formatDef[1], e); } } final ExplorerNode<?> explorernode = (ExplorerNode<?>) oValue; DefaultTreeCellRenderer lbComp = new DefaultTreeCellRenderer() { private static final long serialVersionUID = 5423600039963175923L; public void paintComponent(java.awt.Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; for (PaintImage paintImage : images) { g2d.drawImage( new ImageIcon(paintImage.image.getContent()).getImage(), getIcon().getIconWidth() + getIconTextGap() + paintImage.x, 1, null); } }; }; JComponent result = (JComponent) lbComp.getTreeCellRendererComponent( tree, oValue, bSelected, bExpanded, bLeaf, iRow, bHasFocus); lbComp.setText(tmp); // set tooltip text: final String sDescription = StringUtils.nullIfEmpty(explorernode.getTreeNode().getDescription()); lbComp.setToolTipText(sDescription); // set icon: final Icon icon = explorernode.getIcon(); // if (icon != null) { lbComp.setIcon(icon); // } if (explorernode instanceof GenericObjectExplorerNode) { final Icon iconRelation = ((GenericObjectExplorerNode) explorernode).getRelationIcon(); if (iconRelation != null) { lbComp.setIcon(new CompositeIcon(iconRelation, icon)); // result = new JPanel(new FlowLayout(FlowLayout.LEFT, 1, 0)); // result.add(new JLabel(iconRelation)); // result.add(lbl); // result.setOpaque(false); } } return result; }