List of usage examples for javax.swing SwingUtilities computeStringWidth
public static int computeStringWidth(FontMetrics fm, String str)
From source file:Main.java
public static void setLabelTop(JLabel label, String str, int width, int height) { Graphics g = label.getGraphics(); label.setText(str);//from w w w . j a v a2 s . co m int strWidth = SwingUtilities.computeStringWidth(g.getFontMetrics(), str); int lX = width / 2 - strWidth / 2; int lY = g.getFont().getSize() / 2; //System.out.printf("\"label\"+%s X:%d,Y:%d\n",str,lX,lY); label.setBounds(lX, lY, strWidth, g.getFont().getSize()); }
From source file:Main.java
public static void setLabelAboveOut(JLabel label, String str, int x, int y, int width) { Graphics g = label.getGraphics(); label.setText(str);//from ww w . j a v a 2 s .c om int strWidth = SwingUtilities.computeStringWidth(g.getFontMetrics(), str); int lX = x + width / 2 - strWidth / 2; int lY = y - g.getFont().getSize(); label.setBounds(lX, lY, strWidth, g.getFont().getSize()); }
From source file:Main.java
public static void setLabelCenter(JLabel label, String str, int width, int height) { Graphics g = label.getGraphics(); Color c = g.getColor();// w ww . j av a 2 s . com g.setColor(Color.BLUE); label.setText(str); int strWidth = SwingUtilities.computeStringWidth(g.getFontMetrics(), str); int lX = width / 2 - strWidth; int lY = g.getFont().getSize() / 2; //System.out.printf("\"label\"+%s X:%d,Y:%d\n",str,lX,lY); label.setBounds(lX, lY, strWidth, g.getFont().getSize()); g.setColor(c); }
From source file:Main.java
public static String getClippedText(String text, FontMetrics fm, int maxWidth) { if ((text == null) || (text.length() == 0)) { return ""; }//from ww w . jav a 2s . c o m 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; }
From source file:Main.java
public static BufferedImage takeScreenShot(Component component, String... watermarks) { Dimension size = component.getSize(); BufferedImage screenshot = new BufferedImage(size.width, size.height, Transparency.OPAQUE); Graphics2D g = screenshot.createGraphics(); g.setClip(0, 0, size.width - 1, size.height - 1); component.update(g);/* www.j av a2 s .c o m*/ FontMetrics fm = g.getFontMetrics(); int y = fm.getDescent(); for (String watermark : watermarks) if (watermark != null) { int x = size.width - SwingUtilities.computeStringWidth(fm, watermark); g.setColor(Color.black); g.drawString(watermark, x, y); g.setColor(Color.white); g.drawString(watermark, x - 1, y - 1); y -= fm.getHeight(); } g.dispose(); return screenshot; }
From source file:Main.java
/** * Returns the string width for a given {@link Font} and string. * /*from www .ja v a2s. c o m*/ * @param aFont * the font to create the string width; * @param aString * the string to get the width for. * @return a string width, >= 0. */ public static int getStringWidth(final Font aFont, final String aString) { final FontMetrics frc = createFontMetrics(aFont); return SwingUtilities.computeStringWidth(frc, aString); }
From source file:Main.java
/** * Returns a string abbreviated according to the length of the available space * in a component./* ww w. java 2 s.com*/ * @param str A string which may need abbreviating. * @param component The component the string will be rendered in. * @return a string abbreviated according to the length of the available space */ public static String abbreviate(String str, JComponent component) { String result = ""; if (component != null) { Graphics g = component.getGraphics(); FontMetrics fm = g.getFontMetrics(component.getFont()); int stringSize = SwingUtilities.computeStringWidth(fm, str); final int border = 48; int availableWidth = component.getWidth() - border; if (stringSize > availableWidth) { final int avCharWidth = fm.charWidth('x'); final int alwaysChop = 5; final int charsToChop = alwaysChop + ((stringSize - availableWidth) / avCharWidth); final int leftPos = (str.length() - charsToChop) / 2; final int maxLength = str.length() - charsToChop; final int left = leftPos > 0 ? leftPos : 0; final int len = maxLength > left ? maxLength : left + 1; result = abbreviate(str, left, len); } else { result = str; } } return result; }
From source file:Main.java
License:asdf
public Dimension getPreferredSize(JComponent c) { FontMetrics metrics = c.getFontMetrics(c.getFont()); String tipText = ((JToolTip) c).getTipText(); if (tipText == null) { tipText = ""; }// w w w. ja v a2s.com Image image = new ImageIcon("yourImage").getImage(); int width = SwingUtilities.computeStringWidth(metrics, tipText); int height = metrics.getHeight() + image.getHeight(c); if (width < image.getWidth(c)) { width = image.getWidth(c); } return new Dimension(width, height); }
From source file:net.sf.mzmine.modules.visualization.scatterplot.scatterplotchart.ScatterPlotRenderer.java
/** * Draws an item label.//from ww w.j a va 2 s . c o m * * @param g2 * the graphics device. * @param orientation * the orientation. * @param dataset * the dataset. * @param series * the series index (zero-based). * @param item * the item index (zero-based). * @param x * the x coordinate (in Java2D space). * @param y * the y coordinate (in Java2D space). * @param negative * indicates a negative value (which affects the item label * position). */ protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation, XYDataset dataset, int series, int item, double x, double y, boolean negative) { XYItemLabelGenerator generator = getItemLabelGenerator(series, item); Font labelFont = getItemLabelFont(series, item); g2.setFont(labelFont); String label = generator.generateLabel(dataset, series, item); if ((label == null) || (label.length() == 0)) return; // get the label position.. ItemLabelPosition position = null; if (!negative) { position = getPositiveItemLabelPosition(series, item); } else { position = getNegativeItemLabelPosition(series, item); } // work out the label anchor point... Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), x, y, orientation); FontMetrics metrics = g2.getFontMetrics(labelFont); int width = SwingUtilities.computeStringWidth(metrics, label) + 2; int height = metrics.getHeight(); int X = (int) (anchorPoint.getX() - (width / 2)); int Y = (int) (anchorPoint.getY() - (height)); g2.setPaint(searchColor); g2.fillRect(X, Y, width, height); super.drawItemLabel(g2, orientation, dataset, series, item, x, y, negative); }
From source file:com.lfv.lanzius.server.WorkspaceView.java
@Override protected void paintComponent(Graphics g) { int w = getWidth(); int h = getHeight(); Document doc = server.getDocument(); Color storedCol = g.getColor(); Font storedFont = g.getFont(); // Fill workspace area g.setColor(getBackground());/*from ww w. ja v a 2 s . c o m*/ g.fillRect(0, 0, w, h); // Should the cached version be updated? int updateDocumentVersion = server.getDocumentVersion(); boolean update = (documentVersion != updateDocumentVersion); // Check if we have cached the latest document version, otherwise cache the terminals if (update) { log.debug("Updating view to version " + updateDocumentVersion); terminalMap.clear(); groupList.clear(); if (doc != null) { synchronized (doc) { // Clear the visible attribute on all groups // except the started or paused ones Element egd = doc.getRootElement().getChild("GroupDefs"); Iterator iter = egd.getChildren().iterator(); while (iter.hasNext()) { Element eg = (Element) iter.next(); boolean isVisible = !DomTools.getAttributeString(eg, "state", "stopped", false) .equals("stopped"); eg.setAttribute("visible", String.valueOf(isVisible)); } // Gather information about terminals and cache it Element etd = doc.getRootElement().getChild("TerminalDefs"); iter = etd.getChildren().iterator(); while (iter.hasNext()) { Element et = (Element) iter.next(); int tid = DomTools.getAttributeInt(et, "id", 0, false); if (tid > 0) { // Create terminal and add it to list Terminal t = new Terminal(tid, DomTools.getAttributeInt(et, "x", 0, false), DomTools.getAttributeInt(et, "y", 0, false), DomTools.getChildText(et, "Name", "T/" + tid, false), DomTools.getAttributeBoolean(et, "online", false, false), DomTools.getAttributeBoolean(et, "selected", false, false)); terminalMap.put(tid, t); // Is the terminal monitored? t.isMonitored = DomTools.getAttributeBoolean(et, "monitored", false, false); // Examine the Player element under PlayerSetup t.groupColor = null; Element ep = DomTools.getElementFromSection(doc, "PlayerSetup", "terminalid", String.valueOf(tid)); // Has linked player for this terminal if (ep != null) { StringBuffer sb = new StringBuffer(); // Append player name sb.append(DomTools.getChildText(ep, "Name", "P/?", true)); sb.append(" ("); // Append role list boolean hasRoles = false; Element ers = ep.getChild("RoleSetup"); if (ers != null) { Iterator iterr = ers.getChildren().iterator(); while (iterr.hasNext()) { Element er = (Element) iterr.next(); String id = er.getAttributeValue("id"); er = DomTools.getElementFromSection(doc, "RoleDefs", "id", id); if (er != null) { sb.append(DomTools.getChildText(er, "Name", "R/" + id, false)); sb.append(", "); hasRoles = true; } } if (hasRoles) { // Trim last comma int len = sb.length(); sb.setLength(Math.max(len - 2, 0)); } sb.append(")"); } t.roles = sb.toString(); // Is the player relocated? t.isRelocated = DomTools.getAttributeBoolean(ep, "relocated", false, false); // Get group name and color Element eg = DomTools.getElementFromSection(doc, "GroupDefs", "id", DomTools.getAttributeString(ep, "groupid", "0", true)); t.groupColor = Color.lightGray; if (eg != null) { String sc = DomTools.getChildText(eg, "Color", null, false); if (sc != null) { try { t.groupColor = Color.decode(sc); } catch (NumberFormatException ex) { log.warn("Invalid color attribute on Group node, defaulting to grey"); } } //t.name += " "+DomTools.getChildText(eg, "Name", "G/"+eg.getAttributeValue("id"), false); t.groupName = DomTools.getChildText(eg, "Name", "G/" + eg.getAttributeValue("id"), false); // This group should now be visible eg.setAttribute("visible", "true"); } else log.warn("Invalid groupid attribute on Player node, defaulting to grey"); } } else log.error("Invalid id attribute on Terminal node, skipping"); } // Gather information about groups and cache it iter = egd.getChildren().iterator(); while (iter.hasNext()) { Element eg = (Element) iter.next(); if (DomTools.getAttributeBoolean(eg, "visible", false, false)) { int gid = DomTools.getAttributeInt(eg, "id", 0, true); if (gid > 0) { Group grp = new Group(gid, DomTools.getChildText(eg, "Name", "G/" + gid, false), DomTools.getAttributeBoolean(eg, "selected", false, false)); groupList.add(grp); // group color String sc = DomTools.getChildText(eg, "Color", null, false); if (sc != null) { try { grp.color = Color.decode(sc); } catch (NumberFormatException ex) { log.warn("Invalid color attribute on Group node, defaulting to grey"); } } // state color grp.stateColor = Color.red; String state = DomTools.getAttributeString(eg, "state", "stopped", false); if (state.equals("started")) grp.stateColor = Color.green; else if (state.equals("paused")) grp.stateColor = Color.orange; } } } } } } if (doc == null) { g.setColor(Color.black); String text = "No configuration loaded. Select 'Load configuration...' from the file menu."; g.drawString(text, (w - SwingUtilities.computeStringWidth(g.getFontMetrics(), text)) / 2, h * 5 / 12); } else { g.setFont(new Font("Dialog", Font.BOLD, 13)); Iterator<Terminal> itert = terminalMap.values().iterator(); while (itert.hasNext()) { Terminal t = itert.next(); // Draw box int b = t.isSelected ? SERVERVIEW_SELECTION_BORDER : 1; g.setColor(Color.black); g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER - b, t.y + SERVERVIEW_SELECTION_BORDER - b, SERVERVIEW_TERMINAL_WIDTH + 2 * b, SERVERVIEW_TERMINAL_HEIGHT + 2 * b); g.setColor(t.groupColor == null ? Color.white : t.groupColor); g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER, t.y + SERVERVIEW_SELECTION_BORDER, SERVERVIEW_TERMINAL_WIDTH, SERVERVIEW_TERMINAL_HEIGHT); // Inner areas Rectangle r = new Rectangle(t.x + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER, t.y + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER, SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER, g.getFontMetrics().getHeight() + 4); g.setColor(Color.white); g.fillRect(r.x, r.y, r.width, r.height); g.fillRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width, SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2); g.setColor(Color.black); g.drawRect(r.x, r.y, r.width, r.height); g.drawRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width, SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2); // Name of terminal and group if (server.isaClient(t.tid)) { g.drawImage(indicatorIsa.getImage(), r.x + r.width - 20, r.y + SERVERVIEW_TERMINAL_HEIGHT - 26, null); } g.drawString(t.name + " " + t.groupName, r.x + 4, r.y + r.height - 4); double px = r.x + 4; double py = r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 5; // Draw monitored indicator if (t.isMonitored) { g.drawImage(indicatorMonitored.getImage(), r.x + r.width - 9, r.y + 3, null); } // Draw relocated indicator if (t.isRelocated) { g.drawImage(indicatorRelocated.getImage(), r.x + r.width - 9, r.y + 13, null); } // Draw online indicator r.setBounds(r.x, r.y + r.height, r.width, 3); g.setColor(t.isOnline ? Color.green : Color.red); g.fillRect(r.x, r.y, r.width, r.height); g.setColor(Color.black); g.drawRect(r.x, r.y, r.width, r.height); // Roles if (t.roles.length() > 0) { LineBreakMeasurer lbm = new LineBreakMeasurer(new AttributedString(t.roles).getIterator(), new FontRenderContext(null, false, true)); TextLayout layout; while ((layout = lbm .nextLayout(SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER)) != null) { if (py < t.y + SERVERVIEW_TERMINAL_HEIGHT) { py += layout.getAscent(); layout.draw((Graphics2D) g, (int) px, (int) py); py += layout.getDescent() + layout.getLeading(); } } } } // Draw group indicators int nbrGroupsInRow = w / (2 * Constants.SERVERVIEW_SELECTION_BORDER + 2 + Constants.SERVERVIEW_GROUP_WIDTH); if (nbrGroupsInRow < 1) nbrGroupsInRow = 1; int nbrGroupRows = (groupList.size() + nbrGroupsInRow - 1) / nbrGroupsInRow; int innerWidth = Constants.SERVERVIEW_GROUP_WIDTH; int innerHeight = g.getFontMetrics().getHeight() + 5; int outerWidth = innerWidth + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2; int outerHeight = innerHeight + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2; int x = 0; int y = h - outerHeight * nbrGroupRows; g.setColor(Color.white); g.fillRect(0, y, w, h - y); g.setColor(Color.black); g.drawLine(0, y - 1, w - 1, y - 1); Iterator<Group> iterg = groupList.iterator(); while (iterg.hasNext()) { Group grp = iterg.next(); // Group box grp.boundingRect.setBounds(x, y, outerWidth, outerHeight); int b = grp.isSelected ? Constants.SERVERVIEW_SELECTION_BORDER : 1; g.setColor(Color.black); g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER - b + 1, y + Constants.SERVERVIEW_SELECTION_BORDER - b + 1, innerWidth + 2 * b, innerHeight + 2 * b); g.setColor(grp.color); g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1, y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, innerHeight); g.setColor(Color.black); g.drawString(grp.name, x + Constants.SERVERVIEW_SELECTION_BORDER + 4, y + Constants.SERVERVIEW_SELECTION_BORDER + innerHeight - 4 + 1); // Draw started indicator g.setColor(grp.stateColor); g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1, y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, 2); g.setColor(Color.black); g.drawLine(x + Constants.SERVERVIEW_SELECTION_BORDER + 1, y + Constants.SERVERVIEW_SELECTION_BORDER + 3, x + Constants.SERVERVIEW_SELECTION_BORDER + 1 + innerWidth, y + Constants.SERVERVIEW_SELECTION_BORDER + 3); x += outerWidth; if ((x + outerWidth) > w) { x = 0; y += outerHeight; } } } // Store cached version documentVersion = updateDocumentVersion; g.setColor(storedCol); g.setFont(storedFont); }