/** * Draws as much as possible of a given string into a 2d square region in a graphical space. * * @param g component onto which to draw * @param f font to use in drawing the string * @param s string to be drawn * @param xPos * @param yPos * @param width * @param height */ public static void drawStringMultiline( Graphics2D g, Font f, String s, double xPos, double yPos, double width, double height) { FontMetrics fm = g.getFontMetrics(f); int w = fm.stringWidth(s); int h = fm.getAscent(); // g.setColor(Color.LIGHT_GRAY); g.setColor(Color.BLACK); g.setFont(f); Scanner lineSplitter = new Scanner(s); // draw as much as can fit in each item // read all content from scanner, storing in string lists (where each string == 1 line), each // string should be as long as possible without overflowing the space int maxRows = (int) height / h; List<String> textRows = new ArrayList<>(); while (lineSplitter.hasNextLine() && textRows.size() < maxRows) { String line = lineSplitter.nextLine(); // if line is blank, insert to maintain paragraph seps if (line.trim().equals("")) { textRows.add(""); } // else, pass to inner loop StringBuilder currentBuilder = new StringBuilder(); int currentStrWidth = 0; Scanner splitter = new Scanner(line); while (splitter.hasNext() && textRows.size() < maxRows) { String token = splitter.next() + " "; // TODO incorporate weight detection, formatting for token? currentStrWidth += fm.stringWidth(token); if (currentStrWidth >= width) { // if string length >= glyph width, build row textRows.add(currentBuilder.toString()); currentBuilder = new StringBuilder(); currentBuilder.append(token); currentStrWidth = fm.stringWidth(token); } else { // if not yet at end of row, append to builder currentBuilder.append(token); } } // if we've still space and still have things to write, add them here if (textRows.size() < maxRows) { textRows.add(currentBuilder.toString()); currentBuilder = new StringBuilder(); currentStrWidth = 0; } } // write each line to object for (int t = 0; t < textRows.size(); t++) { String line = textRows.get(t); if (fm.stringWidth(line) <= width) { // ensure that string doesn't overflow the box // g.drawString(line, (float) (xPos-(width/2.)), (float) (yPos-(height/2.) + // h * (t+1))); g.drawString(line, (float) xPos, (float) (yPos + h * (t + 1))); } } }
public void paintComponent(Graphics g) { g.setColor(new Color(96, 96, 96)); image.paintIcon(this, g, 1, 1); FontMetrics fm = g.getFontMetrics(); String[] args = {jEdit.getVersion()}; String version = jEdit.getProperty("about.version", args); g.drawString(version, (getWidth() - fm.stringWidth(version)) / 2, getHeight() - 5); g = g.create((getWidth() - maxWidth) / 2, TOP, maxWidth, getHeight() - TOP - BOTTOM); int height = fm.getHeight(); int firstLine = scrollPosition / height; int firstLineOffset = height - scrollPosition % height; int lines = (getHeight() - TOP - BOTTOM) / height; int y = firstLineOffset; for (int i = 0; i <= lines; i++) { if (i + firstLine >= 0 && i + firstLine < text.size()) { String line = (String) text.get(i + firstLine); g.drawString(line, (maxWidth - fm.stringWidth(line)) / 2, y); } y += fm.getHeight(); } }
private SelectionDialog( RunnerAndConfigurationSettings selectedSettings, @NotNull List<RunnerAndConfigurationSettings> settings) { super(myProject); setTitle(ExecutionBundle.message("before.launch.run.another.configuration.choose")); mySelectedSettings = selectedSettings; mySettings = settings; init(); myJBList.setSelectedValue(mySelectedSettings, true); myJBList.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { doOKAction(); } } }); FontMetrics fontMetrics = myJBList.getFontMetrics(myJBList.getFont()); int maxWidth = fontMetrics.stringWidth("m") * 30; for (RunnerAndConfigurationSettings setting : settings) { maxWidth = Math.max(fontMetrics.stringWidth(setting.getConfiguration().getName()), maxWidth); } maxWidth += 24; // icon and gap myJBList.setMinimumSize(new Dimension(maxWidth, myJBList.getPreferredSize().height)); }
private void paintCoords(int xSize, int ySize) { float yStep = 1; while ((yStep * (ySize - 50) / (threshold - lowThreshold)) < 20) yStep += 1; FontMetrics metrics = g.getFontMetrics(); int height = metrics.getAscent(); for (float y = lowThreshold; y < threshold; y += yStep) { int yCoord = 10 + (int) ((y - lowThreshold) * (ySize - 50) / (threshold - lowThreshold)); g.setColor(Color.LIGHT_GRAY); g.drawLine(45, yCoord, xSize, yCoord); g.setColor(Color.BLACK); String text = "" + y; text = trimStringToLength(text, 5); int width = metrics.stringWidth(text); g.drawString(text, 40 - width, yCoord + height / 2); } g.setColor(Color.LIGHT_GRAY); g.drawLine(45, ySize - 40, xSize, ySize - 40); g.setColor(Color.BLACK); String text = "" + threshold; text = trimStringToLength(text, 5); int width = metrics.stringWidth(text); g.drawString(text, 40 - width, ySize - 40 + height / 2); g.drawLine(45, 10, 45, ySize - 35); g.drawLine(45, ySize - 35, xSize, ySize - 35); }
void setPosition(int newX, int newY) { Insets insets = eNode.getContext().getInsets(); FontMetrics metrics = getFontMetrics(getFont()); int stringWidth = metrics.stringWidth(getText()); int stringHeight = metrics.getHeight(); setBounds( newX + insets.left + eNode.getWidth() + SEPARATION, newY + insets.top + eNode.getInsets().top, metrics.stringWidth(getText()), metrics.getHeight()); }
public static int[] getTextDims(Graphics2D g, Font f, String s) { // [0] == max width of all lines // [1] == total height int[] textDims = new int[2]; FontMetrics fm = g.getFontMetrics(f); int lineH = fm.getAscent(); Scanner lineSplitter = new Scanner(s); int maxW = -1; int lineCounter = 0; while (lineSplitter.hasNextLine()) { String line = lineSplitter.nextLine(); int w = fm.stringWidth(line); if (w > maxW) { maxW = w; } lineCounter++; } int h = lineH * lineCounter; textDims[0] = maxW; textDims[1] = h; return textDims; }
public void paint(Graphics g) { m_fm = g.getFontMetrics(); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight()); g.setColor(getForeground()); g.setFont(getFont()); m_insets = getInsets(); int x = m_insets.left; int y = m_insets.top + m_fm.getAscent(); StringTokenizer st = new StringTokenizer(getText(), "\t"); while (st.hasMoreTokens()) { String sNext = st.nextToken(); g.drawString(sNext, x, y); x += m_fm.stringWidth(sNext); if (!st.hasMoreTokens()) break; int index = 0; while (x >= getTab(index)) index++; x = getTab(index); } }
void drawRoiLabel(Graphics g, int index, Roi roi) { Rectangle r = roi.getBounds(); int x = screenX(r.x); int y = screenY(r.y); double mag = getMagnification(); int width = (int) (r.width * mag); int height = (int) (r.height * mag); int size = width > 40 && height > 40 ? 12 : 9; if (font != null) { g.setFont(font); size = font.getSize(); } else if (size == 12) g.setFont(largeFont); else g.setFont(smallFont); boolean drawingList = index >= LIST_OFFSET; if (drawingList) index -= LIST_OFFSET; String label = "" + (index + 1); if (drawNames && roi.getName() != null) label = roi.getName(); FontMetrics metrics = g.getFontMetrics(); int w = metrics.stringWidth(label); x = x + width / 2 - w / 2; y = y + height / 2 + Math.max(size / 2, 6); int h = metrics.getAscent() + metrics.getDescent(); if (bgColor != null) { g.setColor(bgColor); g.fillRoundRect(x - 1, y - h + 2, w + 1, h - 3, 5, 5); } if (!drawingList && labelRects != null && index < labelRects.length) labelRects[index] = new Rectangle(x - 1, y - h + 2, w + 1, h); g.setColor(labelColor); g.drawString(label, x, y - 2); g.setColor(defaultColor); }
/** @see prefuse.render.AbstractShapeRenderer#getRawShape(prefuse.visual.VisualItem) */ @Override protected Shape getRawShape(VisualItem item) { double x1 = item.getDouble(VisualItem.X); double y1 = item.getDouble(VisualItem.Y); double x2 = item.getDouble(VisualItem.X2); double y2 = item.getDouble(VisualItem.Y2); boolean isX = item.getBoolean(DocumentGridAxisLayout.IS_X); double midPoint = item.getDouble(DocumentGridAxisLayout.MID_POINT); // horizontal or vertical coords should be manually held constant so that fisheye works // properly if (isX) { // vertical line m_line.setLine(x1, y1, x1, y2); } else { // horizontal line m_line.setLine(x1, y1, x2, y1); } if (!item.canGetString(VisualItem.LABEL)) { return m_line; } String label = item.getString(VisualItem.LABEL); if (label == null) { return m_line; } FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(item.getFont()); m_ascent = fm.getAscent(); int h = fm.getHeight(); int w = fm.stringWidth(label); double tx, ty; int labelOffset = 10; if (isX) { // vertical axis // get text x-coord, center at midPoint // tx = x1 + (x2-x1)/2 - w/2; // tx = midPoint + (x1+midPoint)/2 - w/2; // tx = x1 + midPoint/2 - w/2; // simpler approach: just add a fixed distance tx = x1 + labelOffset; // get text y-coord ty = y2 - h; } else { // horiz axis // get text x-coord tx = x1 - w - 2; // get text y-coord, center at midPoint // ty = y1 + (y2-y1)/2 - h/2; // ty = y1 + midPoint/2 - h/2; // simpler approach: just add a fixed distance ty = y1 + labelOffset; } m_box.setFrame(tx, ty, w, h); return m_box; }
private void setFixedColumnWidth(final int columnIndex, String sampleText) { final TableColumn column = myEntryTable.getTableHeader().getColumnModel().getColumn(columnIndex); final FontMetrics fontMetrics = myEntryTable.getFontMetrics(myEntryTable.getFont()); final int width = fontMetrics.stringWidth(" " + sampleText + " ") + JBUI.scale(4); column.setPreferredWidth(width); column.setMinWidth(width); column.setResizable(false); }
/** * Query the font width used in calculating line indenting. * * @return fontWidth to use to calculate line indenting. */ public int getFontWidth() { int retval = fontWidth; if (fontWidth < 0) { final FontMetrics fontMetrics = getFontMetrics(getFont()); retval = fontMetrics.stringWidth("_"); setFontWidth(retval); } return retval; }
/** * Draws this process as a colored box with a process ID inside. * * @param g The graphics context. * @param x The leftmost x-coordinate of the box. * @param y The topmost y-coordinate of the box. * @param w The width of the box. * @param h The height of the box. */ public void draw(Graphics g, int x, int y, int w, int h) { g.setColor(color); g.fillRect(x, y, w, h); g.setColor(Color.black); g.drawRect(x, y, w, h); g.setFont(font); FontMetrics fm = g.getFontMetrics(font); g.drawString( "" + processId, x + w / 2 - fm.stringWidth("" + processId) / 2, y + h / 2 + fm.getHeight() / 2); }
/** This internal method begins a new page and prints the header. */ protected void newpage() { page = job.getGraphics(); // Begin the new page linenum = 0; charnum = 0; // Reset line and char number pagenum++; // Increment page number page.setFont(headerfont); // Set the header font. page.drawString(jobname, x0, headery); // Print job name left justified String s = "- " + pagenum + " -"; // Print the page number centered. int w = headermetrics.stringWidth(s); page.drawString(s, x0 + (this.width - w) / 2, headery); w = headermetrics.stringWidth(time); // Print date right justified page.drawString(time, x0 + width - w, headery); // Draw a line beneath the header int y = headery + headermetrics.getDescent() + 1; page.drawLine(x0, y, x0 + width, y); // Set the basic monospaced font for the rest of the page. page.setFont(font); }
private void measure() { FontMetrics fontmetrics = getFontMetrics(getFont()); if (fontmetrics == null) return; line_height = fontmetrics.getHeight(); line_ascent = fontmetrics.getAscent(); max_width = 0; for (int i = 0; i < num_lines; i++) { line_widths[i] = fontmetrics.stringWidth(lines[i]); if (line_widths[i] > max_width) max_width = line_widths[i]; } max_width += 2 * btnMarginWidth; max_height = num_lines * line_height + 2 * btnMarginHeight; }
void setPosition(int newX, int newY) { Insets insets = getContext().getInsets(); insets = getContext().getInsets(); FontMetrics metrics = getFontMetrics(getFont()); int stringWidth = metrics.stringWidth(getText()); int stringHeight = metrics.getHeight(); setBounds( newX + insets.left, newY + insets.top, stringWidth + getInsets().left + getInsets().right, stringHeight + insets.top + insets.bottom + VERTICAL_PAD); if (rightLabel != null) rightLabel.setPosition(newX, newY); }
/* paint() - get current time and draw (centered) in Component. */ public void paint(Graphics g) { Calendar myCal = Calendar.getInstance(); StringBuffer sb = new StringBuffer(); sb.append(tf.format(myCal.get(Calendar.HOUR))); sb.append(':'); sb.append(tflz.format(myCal.get(Calendar.MINUTE))); sb.append(':'); sb.append(tflz.format(myCal.get(Calendar.SECOND))); String s = sb.toString(); FontMetrics fm = getFontMetrics(getFont()); int x = (getSize().width - fm.stringWidth(s)) / 2; // System.out.println("Size is " + getSize()); g.drawString(s, x, 10); }
public void centerText(String s1, String s2, Graphics g, Color c, int x, int y, int w, int h) { // locs[0].centerText(s1, s2, this.getGraphics(), // Color.white, 400,0,200,50); // g.setXORMode(unselected_color); // centerText("pic" + im, null, g, Color.black, x, y, w, h); Font f = g.getFont(); FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(f); int ascent = fm.getAscent(); int height = fm.getHeight(); int width1 = 0, width2 = 0, x0 = 0, x1 = 0, y0 = 0, y1 = 0; width1 = fm.stringWidth(s1); if (s2 != null) width2 = fm.stringWidth(s2); x0 = x + (w - width1) / 2; x0 = x + (w - width2) / 2; if (s2 == null) y0 = y + (h - height) / 2 + ascent; else { y0 = y + (h - (int) (height * 2.2)) / 2 + ascent; y1 = y0 + (int) (height * 1.2); } g.setColor(c); g.drawString(s1, x0, y0); if (s2 != null) g.drawString(s2, x1, y1); }
// called whenever the TreeDisplay must be drawn on the screen public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = getSize(); // draw white background g2.setPaint(Color.white); g2.fill(new Rectangle2D.Double(0, 0, d.width, d.height)); int depth = h(); if (root == null) // no tree to draw return; // hack to avoid division by zero, if only one level in tree if (depth == 1) depth = 2; // compute the size of the text FontMetrics font = g2.getFontMetrics(); TreeNode<E> leftmost = root; while (leftmost.left != null) leftmost = leftmost.left; TreeNode<E> rightmost = root; while (rightmost.right != null) rightmost = rightmost.right; int leftPad = font.stringWidth(leftmost.data + "") / 2; int rightPad = font.stringWidth(rightmost.data + "") / 2; int textHeight = font.getHeight(); // draw the actual tree drawTree( g2, root, leftPad + ARC_PAD, d.width - rightPad - ARC_PAD, textHeight / 2 + ARC_PAD, (d.height - textHeight - 2 * ARC_PAD) / (depth - 1)); }
private void recalculateDimension() { FontMetrics fontmetrics = getFontMetrics(getFont()); lineHeight = fontmetrics.getHeight(); lineAscent = fontmetrics.getAscent(); maxWidth = 0; for (int i = 0; i < numLines; i++) { lineWidths[i] = fontmetrics.stringWidth(lines[i]); maxWidth = Math.max(maxWidth, lineWidths[i]); } maxWidth += 2 * btnMarginWidth; textHeight = numLines * lineHeight; }
// draws the tree, starting from the given node, in the region with x values // ranging // from minX to maxX, with y value beginning at y, and next level at y + // yIncr. private void drawTree(Graphics2D g2, TreeNode<E> t, int minX, int maxX, int y, int yIncr) { // skip if empty if (t == null) return; // compute useful coordinates int x = (minX + maxX) / 2; int nextY = y + yIncr; // draw black lines g2.setPaint(Color.black); if (t.left != null) { int nextX = (minX + x) / 2; g2.draw(new Line2D.Double(x, y, nextX, nextY)); } if (t.right != null) { int nextX = (x + maxX) / 2; g2.draw(new Line2D.Double(x, y, nextX, nextY)); } // measure text FontMetrics font = g2.getFontMetrics(); String text = t.data + ""; int textHeight = font.getHeight(); int textWidth = font.stringWidth(text); // draw the box around the node Rectangle2D.Double box = new Rectangle2D.Double( x - textWidth / 2 - ARC_PAD, y - textHeight / 2 - ARC_PAD, textWidth + 2 * ARC_PAD, textHeight + 2 * ARC_PAD); Color c = new Color(187, 224, 227); g2.setPaint(c); g2.fill(box); // draw black border g2.setPaint(Color.black); g2.draw(box); // draw text g2.drawString(text, x - textWidth / 2, y + textHeight / 2); // draw children drawTree(g2, t.left, minX, x, nextY, yIncr); drawTree(g2, t.right, x, maxX, nextY, yIncr); }
private void drawTile(Graphics g2, Tile tile, int x, int y) { Graphics2D g = ((Graphics2D) g2); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); int value = tile.value; int xOffset = offsetCoors(x); int yOffset = offsetCoors(y); g.setColor(tile.getBackground()); g.fillRoundRect(xOffset, yOffset, TILE_SIZE, TILE_SIZE, 14, 14); g.setColor(tile.getForeground()); final int size = value < 100 ? 36 : value < 1000 ? 32 : 24; final Font font = new Font(FONT_NAME, Font.BOLD, size); g.setFont(font); String s = String.valueOf(value); final FontMetrics fm = getFontMetrics(font); final int w = fm.stringWidth(s); final int h = -(int) fm.getLineMetrics(s, g).getBaselineOffsets()[2]; if (value != 0) g.drawString(s, xOffset + (TILE_SIZE - w) / 2, yOffset + TILE_SIZE - (TILE_SIZE - h) / 2 - 2); if (myWin || myLose) { g.setColor(new Color(255, 255, 255, 30)); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(78, 139, 202)); g.setFont(new Font(FONT_NAME, Font.BOLD, 48)); if (myWin) { g.drawString("You won!", 68, 150); } if (myLose) { g.drawString("Game over!", 50, 130); g.drawString("You lose!", 64, 200); } if (myWin || myLose) { g.setFont(new Font(FONT_NAME, Font.PLAIN, 16)); g.setColor(new Color(128, 128, 128, 128)); g.drawString("Press ESC to play again", 80, getHeight() - 40); } } g.setFont(new Font(FONT_NAME, Font.PLAIN, 18)); g.drawString("Score: " + myScore, 200, 365); }
/** * Called to paint the outline. * * @param g graphics object to paint. */ public void paint(final Graphics g) { final FontMetrics fontMetrics = getFontMetrics(getFont()); setFontWidth(fontMetrics.stringWidth("_")); setFontHeight(fontMetrics.getHeight()); if (firstTime) { firstTime = false; setVisible("Outline".equalsIgnoreCase(djvuBean.properties.getProperty("navpane"))); } if (!isVisible()) { getParent().setVisible(false); invalidate(); djvuBean.recursiveRevalidate(); } else { synchronized (activeVector) { paintItem(0, g, getBookmark(0)); paintCheckbox(0, g, getBookmark(0)); } } }
AboutPanel() { setFont(UIManager.getFont("Label.font")); fm = getFontMetrics(getFont()); setForeground(new Color(96, 96, 96)); image = new ImageIcon(getClass().getResource("/org/gjt/sp/jedit/icons/about.png")); setBorder(new MatteBorder(1, 1, 1, 1, Color.gray)); text = new Vector(50); StringTokenizer st = new StringTokenizer(jEdit.getProperty("about.text"), "\n"); while (st.hasMoreTokens()) { String line = st.nextToken(); text.addElement(line); maxWidth = Math.max(maxWidth, fm.stringWidth(line) + 10); } scrollPosition = -250; thread = new AnimationThread(); }
private int getTextWidth(String text) { return fmRef.stringWidth(text); }
/** * Draw the text and graph. * * @param g */ @Override public void paintComponent(Graphics g) { locations.clear(); // Background g.setColor(background_color); g.fillRect(0, 0, getWidth(), getHeight()); // This color is used for everything until drawing the points g.setColor(foreground_color); // Anti-Aliasing Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Font FontMetrics fontMetrics = g.getFontMetrics(FONT); int fontHeight = fontMetrics.getHeight(); g.setFont(FONT); int topTextY = fontMetrics.getAscent(); // Margins int vMargin = fontHeight + MARGIN; int hMargin = MARGIN; // Calculate actual usable size double width = getWidth() - hMargin * 2; double height = getHeight() - vMargin * 2; boolean drawLowerLine = height > -vMargin; // If there is any data and no hovered entry is shown, draw current // viewercount int nowTextX = 0; if (history != null && hoverEntry == -1) { Integer viewers = history.get(endTime).getViewers(); long ago = System.currentTimeMillis() - endTime; String text; if (ago > CONSIDERED_AS_NOW) { text = "latest: " + Helper.formatViewerCount(viewers); } else { text = "now: " + Helper.formatViewerCount(viewers); } if (viewers == -1) { text = "Stream offline"; } nowTextX = getWidth() - fontMetrics.stringWidth(text); g.drawString(text, nowTextX, topTextY); } // Default text when no data is present if (history == null || history.size() < 2) { String text = "No viewer history yet"; int textWidth = fontMetrics.stringWidth(text); int y = getHeight() / 2 + fontMetrics.getDescent(); int x = (getWidth() - textWidth) / 2; boolean drawInfoText = false; if (history != null && y < topTextY + fontHeight + 4 && x + textWidth + 7 > nowTextX) { if (drawLowerLine || nowTextX > textWidth + 5) { if (drawLowerLine) { y = getHeight() - 2; } else { y = topTextY; } x = 0; drawInfoText = true; } } else { drawInfoText = true; } if (drawInfoText) { g.drawString(text, x, y); } return; } // ---------- // From here only when actual data is to be rendered // Show info on hovered entry String maxValueText = "max: " + Helper.formatViewerCount(maxValue); int maxValueEnd = fontMetrics.stringWidth(maxValueText); boolean displayMaxValue = true; if (hoverEntry != -1) { Integer viewers = history.get(hoverEntry).getViewers(); Date d = new Date(hoverEntry); String text = "Viewers: " + Helper.formatViewerCount(viewers) + " (" + sdf.format(d) + ")"; if (viewers == -1) { text = "Stream offline (" + sdf.format(d) + ")"; } int x = getWidth() - fontMetrics.stringWidth(text); if (maxValueEnd > x) { displayMaxValue = false; } g.drawString(text, x, topTextY); } String minText = "min: " + Helper.formatViewerCount(minValue); int minTextWidth = fontMetrics.stringWidth(minText); // Draw Times if (drawLowerLine) { String timeText = makeTimesText(startTime, endTime); int timeTextWidth = fontMetrics.stringWidth(timeText); int textX = getWidth() - timeTextWidth; g.drawString(timeText, textX, getHeight() - 1); if (minValue >= 1000 && timeTextWidth + minTextWidth > width) { minText = "min: " + minValue / 1000 + "k"; } } // Draw min/max if necessary if (isShowingInfo()) { if (displayMaxValue) { g.drawString(maxValueText, 0, topTextY); } if (drawLowerLine) { g.drawString(minText, 0, getHeight() - 1); } else if (maxValueEnd + minTextWidth + 29 < nowTextX) { g.drawString(minText, maxValueEnd + 10, topTextY); } } // If height available for the graph is too small, don't draw graph if (height < 5) { return; } // Calculation factors for calculating the points location int range = maxValue - minValue; if (showFullRange) { range = maxValue; } if (range == 0) { // Prevent division by zero range = 1; } double pixelPerViewer = height / range; double pixelPerTime = width / duration; // Go through all entries and calculate positions int prevX = -1; int prevY = -1; Iterator<Entry<Long, StreamInfoHistoryItem>> it = history.entrySet().iterator(); while (it.hasNext()) { Entry<Long, StreamInfoHistoryItem> entry = it.next(); // Get time and value to draw next long time = entry.getKey(); if (time < startTime || time > endTime) { continue; } long offsetTime = time - startTime; int viewers = entry.getValue().getViewers(); if (viewers == -1) { viewers = 0; } // Calculate point location int x = (int) (hMargin + offsetTime * pixelPerTime); int y; if (showFullRange) { y = (int) (-vMargin + getHeight() - (viewers) * pixelPerViewer); } else { y = (int) (-vMargin + getHeight() - (viewers - minValue) * pixelPerViewer); } // Draw connecting line if (prevX != -1) { g.drawLine(x, y, prevX, prevY); } // Save point coordinates to be able to draw the line next loop prevX = x; prevY = y; // Save point locations to draw points and to find entries on hover locations.put(new Point(x, y), time); } // Draw points (after lines, so they are in front) for (Point point : locations.keySet()) { int x = point.x; int y = point.y; long seconds = locations.get(point); StreamInfoHistoryItem historyObject = history.get(seconds); // Highlight hovered entry if (seconds == hoverEntry) { g.setColor(HOVER_COLOR); } else { // Draw offline points differently if (!historyObject.isOnline()) { g.setColor(OFFLINE_COLOR); } else { g.setColor(colors.get(seconds)); } } g.fillOval(x - POINT_SIZE / 2, y - POINT_SIZE / 2, POINT_SIZE, POINT_SIZE); } }
/** The method to call when the thread starts */ public void run() { boolean draw = true; FontMetrics fm; Rectangle r; int sw = 0; int sa = 0; int x = 0; int y = 0; setPriority(Thread.MIN_PRIORITY); while (true) { if (newmessage != null && draw) { message = newmessage; newmessage = null; } if (lg == null) { lg = g2d.getGraphics(); if (lg != null) lg = lg.create(); } if (lg != null) { if (f != null) lg.setFont(f); fm = lg.getFontMetrics(lg.getFont()); sw = fm.stringWidth(message); sa = fm.getAscent(); } else { draw = false; } if (draw) { lg.setColor(foreground); r = g2d.bounds(); x = r.x + (r.width - sw) / 2; y = r.y + (r.height + sa) / 2; lg.drawString(message, x, y); g2d.repaint(); try { sleep(visible); } catch (Exception e) { } } else { if (lg != null) { lg.setColor(g2d.getBackground()); lg.drawString(message, x, y); g2d.repaint(); } try { sleep(invisible); } catch (Exception e) { } } draw = !draw; } }
/** * Wrapper method around the <tt>paintText()</tt> method of the <tt>VisualEdgePainter</tt> * interface. This method performs the calculation to determine the position where the text will * be drawn. */ private void paintText(VisualEdge vEdge, Graphics2D g2d) { Point fromPoint = new Point(); Point toPoint = new Point(); GeneralPath gPath = vEdge.getGeneralPath(); PathIterator iterator = gPath.getPathIterator(null); FontMetrics fontMetrics; float edgeSegment[] = new float[6]; double currentLength = 0; float cumulativeLength = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; int segmentType; boolean firstPointInitialized = false; // Get the total length of the edge float edgeLength = vEdge.getEdgeLength(vEdge, fromPoint, toPoint); while (!iterator.isDone()) { segmentType = iterator.currentSegment(edgeSegment); switch (segmentType) { case PathIterator.SEG_LINETO: case PathIterator.SEG_MOVETO: x2 = edgeSegment[0]; y2 = edgeSegment[1]; break; case PathIterator.SEG_QUADTO: x2 = edgeSegment[2]; y2 = edgeSegment[3]; break; case PathIterator.SEG_CUBICTO: x2 = edgeSegment[4]; y2 = edgeSegment[5]; } if (firstPointInitialized) { currentLength = Point2D.distance(x1, y1, x2, y2); cumulativeLength += currentLength; } iterator.next(); // If we are halfway through the length of the edge, // then paint the text if (cumulativeLength >= (edgeLength / 2) || cumulativeLength >= edgeLength) { // Ratio of the remaining half-length over the length of the current edge double ratio = ((edgeLength / 2) - (cumulativeLength - currentLength)) / currentLength; fontMetrics = vEdge.getFontMetrics(); // Take into account the text's length this.paintText( g2d, vEdge.getFont(), vEdge.getFontcolor(), vEdge.getLabel(), (float) (fromPoint.getX() < toPoint.getX() ? (x1 + (Math.abs(x2 - x1) * ratio)) : (x1 - (Math.abs(x2 - x1) * ratio))) - fontMetrics.stringWidth(vEdge.getLabel()) / 2, (float) (fromPoint.getY() < toPoint.getY() ? (y1 + (Math.abs(y2 - y1) * ratio)) : (y1 - (Math.abs(y2 - y1) * ratio)))); break; } x1 = x2; y1 = y2; if (!firstPointInitialized) { firstPointInitialized = true; } } }
private Coord strsize(String text) { return (new Coord(m.stringWidth(text), height())); }
public ProcessedModulesTable(final Project project) { super(new BorderLayout()); myTableModel = new MyTableModel(project); myTable = new JBTable(myTableModel); myTable.getEmptyText().setText("No modules configured"); // myTable.setShowGrid(false); myTable.setIntercellSpacing(JBUI.emptySize()); myTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); myTable.setColumnSelectionAllowed(false); final TableColumnModel columnModel = myTable.getColumnModel(); final TableColumn dirNameColumn = columnModel.getColumn(myTableModel.DIRNAME_COLUMN_INDEX); final String title = "Generated Sources Directory Name"; dirNameColumn.setHeaderValue(title); final JTableHeader tableHeader = myTable.getTableHeader(); final FontMetrics metrics = tableHeader.getFontMetrics(tableHeader.getFont()); final int preferredWidth = metrics.stringWidth(title) + 12; dirNameColumn.setPreferredWidth(preferredWidth); dirNameColumn.setMaxWidth(preferredWidth + 20); dirNameColumn.setCellRenderer(new MyElementColumnCellRenderer()); final TableColumn moduleColumn = columnModel.getColumn(myTableModel.ELEMENT_COLUMN_INDEX); moduleColumn.setHeaderValue("Module"); moduleColumn.setCellRenderer(new MyElementColumnCellRenderer()); final JPanel panel = ToolbarDecorator.createDecorator(myTable) .disableUpDownActions() .setPreferredSize(JBUI.size(100, 155)) .createPanel(); add(panel, BorderLayout.CENTER); final SpeedSearchBase<JBTable> speedSearch = new SpeedSearchBase<JBTable>(myTable) { public int getSelectedIndex() { return myTable.getSelectedRow(); } @Override protected int convertIndexToModel(int viewIndex) { return myTable.convertRowIndexToModel(viewIndex); } public Object[] getAllElements() { final int count = myTableModel.getRowCount(); Object[] elements = new Object[count]; for (int idx = 0; idx < count; idx++) { elements[idx] = myTableModel.getModuleAt(idx); } return elements; } public String getElementText(Object element) { return ((Module) element).getName() + " (" + FileUtil.toSystemDependentName(((Module) element).getModuleFilePath()) + ")"; } public void selectElement(Object element, String selectedText) { final int count = myTableModel.getRowCount(); for (int row = 0; row < count; row++) { if (element.equals(myTableModel.getModuleAt(row))) { final int viewRow = myTable.convertRowIndexToView(row); myTable.getSelectionModel().setSelectionInterval(viewRow, viewRow); TableUtil.scrollSelectionToVisible(myTable); break; } } } }; speedSearch.setComparator(new SpeedSearchComparator(false)); }
public int advance(int pos) { return (m.stringWidth(text.substring(0, pos))); }