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); }
public ColorPane() { super(); Font font = new Font("Monospaced", Font.PLAIN, 12); FontMetrics fm = getFontMetrics(font); lineHeight = fm.getHeight(); setFont(font); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); }
/** * Write the given text string in the current font, left-aligned at (x, y). * * @param x the x-coordinate of the text * @param y the y-coordinate of the text * @param s the text */ public static void textLeft(double x, double y, String s) { offscreen.setFont(font); FontMetrics metrics = offscreen.getFontMetrics(); double xs = scaleX(x); double ys = scaleY(y); int hs = metrics.getDescent(); offscreen.drawString(s, (float) (xs), (float) (ys + hs)); draw(); }
private void adjustCanvasStuff() { Font f = parent.frameFont; setFont(f); fm = getToolkit().getFontMetrics(f); lineSize = fm.getHeight(); rulerHt = 3 * lineSize; zLockStrW = fm.stringWidth("Zoom Lock"); elTimeStrW = fm.stringWidth("Elapsed Time"); fDescent = fm.getDescent(); dpi = getToolkit().getScreenResolution(); }
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; }
private void setTabSize(int charactersPerTab) { FontMetrics fm = this.getFontMetrics(this.getFont()); int charWidth = fm.charWidth('w'); int tabWidth = charWidth * charactersPerTab; TabStop[] tabs = new TabStop[10]; for (int j = 0; j < tabs.length; j++) { int tab = j + 1; tabs[j] = new TabStop(tab * tabWidth); } TabSet tabSet = new TabSet(tabs); SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setFontSize(attributes, 18); StyleConstants.setFontFamily(attributes, "Osaka-Mono"); StyleConstants.setTabSet(attributes, tabSet); int length = getDocument().getLength(); getStyledDocument().setParagraphAttributes(0, length, attributes, true); }
/** 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); }
public TreeDrawCanvas( TreeDisplayable theTarget, Object auxDat, boolean doWin, int fontSize, Color c) { doWindow = doWin; if (doWindow) { ourFont = new Font("MonoSpaced", Font.PLAIN, fontSize); FM = getFontMetrics(ourFont); FontHeight = FM.getMaxAscent() + FM.getMaxDescent(); // setBackground(Color.yellow.brighter()); setBackground(c); } target = theTarget; auxData = auxDat; helpers = new Vector<TDHelper>(); createHelperStruct(target, helpers, 0, auxDat); for (int i = 0; i < helpers.size(); i++) { TDHelper h = helpers.elementAt(i); } if (doWindow) { layoutRects(); } }
public void draw( Graphics2D g, Color stringColor, Color foreground, Color background, String info, double x, double y) { FontMetrics fm = g.getFontMetrics(); int h = fm.getHeight(); int w = fm.stringWidth(info); r1.setRect( x - w / 2 - in.left, y - in.top - h / 2, w + in.right + in.left, h + in.bottom + in.top); g.setColor(background); g.fill(r1); g.setColor(stringColor); g.draw(r1); g.setColor(foreground); r2.setRect(r1.getX() + 1, r1.getY() + 1, r1.getWidth() - 2, r1.getHeight() - 2); g.draw(r2); g.setColor(stringColor); g.drawString( info, (float) (r2.getX() + in.left), (float) (r2.getY() + h - (r2.getHeight() - h) / 2)); }
private final void showpercent(String s, int i, int j) { Graphics g = getGraphics(); Font font = new Font("Helvetica", 1, 13); FontMetrics fontmetrics = getFontMetrics(font); Font font1 = new Font("Helvetica", 0, 13); FontMetrics fontmetrics1 = getFontMetrics(font1); if (all || !img && mt.checkAll(true)) { all = false; if (img || mt.checkAll(true)) { g.drawImage(loading, 0, 0, this); img = true; } else { g.setColor(Color.black); g.fillRect(0, 0, 512, 344); } g.setColor(Color.white); g.setFont(font); String s1 = "RuneScape has been updated!"; g.drawString(s1, 256 - fontmetrics.stringWidth(s1) / 2, 125); s1 = "Please wait - Fetching new files..."; g.drawString(s1, 256 - fontmetrics.stringWidth(s1) / 2, 140); g.setFont(font1); s1 = "This may take a few minutes, but only"; g.drawString(s1, 256 - fontmetrics1.stringWidth(s1) / 2, 165); s1 = "needs to be done when the game is updated."; g.drawString(s1, 256 - fontmetrics1.stringWidth(s1) / 2, 180); } Color color = new Color(140, 17, 17); g.setColor(color); g.drawRect(104, 190, 304, 34); g.fillRect(106, 192, j * 3, 30); g.setColor(Color.black); g.fillRect(106 + j * 3, 192, 300 - j * 3, 30); String s2 = "Loading " + s + " - " + i + "%"; g.setFont(font); g.setColor(Color.white); g.drawString(s2, 256 - fontmetrics.stringWidth(s2) / 2, 212); }
/** * "Fixates" the preferred width of the given label to the given text. * * @param aLabel the label to fixate, cannot be <code>null</code>; * @param aMinimalText the text to use as minimal width indicator. */ public static final void fixLabelWidth(final JLabel aLabel, final String aMinimalText) { final FontMetrics fm = aLabel.getFontMetrics(aLabel.getFont()); final int height = fm.getHeight(); aLabel.setPreferredSize(new Dimension(fm.stringWidth(aMinimalText), height)); }
@Override public void paintComponent(Graphics g) { super.paintComponent(g); int width = getWidth() - rightMargin - leftMargin - 10; int height = getHeight() - topMargin - bottomMargin; if (width <= 0 || height <= 0) { // not enough room to paint anything return; } Color oldColor = g.getColor(); Font oldFont = g.getFont(); Color fg = getForeground(); Color bg = getBackground(); boolean bgIsLight = (bg.getRed() > 200 && bg.getGreen() > 200 && bg.getBlue() > 200); ((Graphics2D) g) .setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (smallFont == null) { smallFont = oldFont.deriveFont(9.0F); } r.x = leftMargin - 5; r.y = topMargin - 8; r.width = getWidth() - leftMargin - rightMargin; r.height = getHeight() - topMargin - bottomMargin + 16; if (border == null) { // By setting colors here, we avoid recalculating them // over and over. border = new BevelBorder( BevelBorder.LOWERED, getBackground().brighter().brighter(), getBackground().brighter(), getBackground().darker().darker(), getBackground().darker()); } border.paintBorder(this, g, r.x, r.y, r.width, r.height); // Fill background color g.setColor(bgColor); g.fillRect(r.x + 2, r.y + 2, r.width - 4, r.height - 4); g.setColor(oldColor); long tMin = Long.MAX_VALUE; long tMax = Long.MIN_VALUE; long vMin = Long.MAX_VALUE; long vMax = 1; int w = getWidth() - rightMargin - leftMargin - 10; int h = getHeight() - topMargin - bottomMargin; if (times.size > 1) { tMin = Math.min(tMin, times.time(0)); tMax = Math.max(tMax, times.time(times.size - 1)); } long viewRangeMS; if (viewRange > 0) { viewRangeMS = viewRange * MINUTE; } else { // Display full time range, but no less than a minute viewRangeMS = Math.max(tMax - tMin, 1 * MINUTE); } // Calculate min/max values for (Sequence seq : seqs) { if (seq.size > 0) { for (int i = 0; i < seq.size; i++) { if (seq.size == 1 || times.time(i) >= tMax - viewRangeMS) { long val = seq.value(i); if (val > Long.MIN_VALUE) { vMax = Math.max(vMax, val); vMin = Math.min(vMin, val); } } } } else { vMin = 0L; } if (unit == Unit.BYTES || !seq.isPlotted) { // We'll scale only to the first (main) value set. // TODO: Use a separate property for this. break; } } // Normalize scale vMax = normalizeMax(vMax); if (vMin > 0) { if (vMax / vMin > 4) { vMin = 0; } else { vMin = normalizeMin(vMin); } } g.setColor(fg); // Axes // Draw vertical axis int x = leftMargin - 18; int y = topMargin; FontMetrics fm = g.getFontMetrics(); g.drawLine(x, y, x, y + h); int n = 5; if (("" + vMax).startsWith("2")) { n = 4; } else if (("" + vMax).startsWith("3")) { n = 6; } else if (("" + vMax).startsWith("4")) { n = 4; } else if (("" + vMax).startsWith("6")) { n = 6; } else if (("" + vMax).startsWith("7")) { n = 7; } else if (("" + vMax).startsWith("8")) { n = 8; } else if (("" + vMax).startsWith("9")) { n = 3; } // Ticks ArrayList<Long> tickValues = new ArrayList<Long>(); tickValues.add(vMin); for (int i = 0; i < n; i++) { long v = i * vMax / n; if (v > vMin) { tickValues.add(v); } } tickValues.add(vMax); n = tickValues.size(); String[] tickStrings = new String[n]; for (int i = 0; i < n; i++) { long v = tickValues.get(i); tickStrings[i] = getSizeString(v, vMax); } // Trim trailing decimal zeroes. if (decimals > 0) { boolean trimLast = true; boolean removedDecimalPoint = false; do { for (String str : tickStrings) { if (!(str.endsWith("0") || str.endsWith("."))) { trimLast = false; break; } } if (trimLast) { if (tickStrings[0].endsWith(".")) { removedDecimalPoint = true; } for (int i = 0; i < n; i++) { String str = tickStrings[i]; tickStrings[i] = str.substring(0, str.length() - 1); } } } while (trimLast && !removedDecimalPoint); } // Draw ticks int lastY = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { long v = tickValues.get(i); y = topMargin + h - (int) (h * (v - vMin) / (vMax - vMin)); g.drawLine(x - 2, y, x + 2, y); String s = tickStrings[i]; if (unit == Unit.PERCENT) { s += "%"; } int sx = x - 6 - fm.stringWidth(s); if (y < lastY - 13) { if (checkLeftMargin(sx)) { // Wait for next repaint return; } g.drawString(s, sx, y + 4); } // Draw horizontal grid line g.setColor(Color.lightGray); g.drawLine(r.x + 4, y, r.x + r.width - 4, y); g.setColor(fg); lastY = y; } // Draw horizontal axis x = leftMargin; y = topMargin + h + 15; g.drawLine(x, y, x + w, y); long t1 = tMax; if (t1 <= 0L) { // No data yet, so draw current time t1 = System.currentTimeMillis(); } long tz = timeDF.getTimeZone().getOffset(t1); long tickInterval = calculateTickInterval(w, 40, viewRangeMS); if (tickInterval > 3 * HOUR) { tickInterval = calculateTickInterval(w, 80, viewRangeMS); } long t0 = tickInterval - (t1 - viewRangeMS + tz) % tickInterval; while (t0 < viewRangeMS) { x = leftMargin + (int) (w * t0 / viewRangeMS); g.drawLine(x, y - 2, x, y + 2); long t = t1 - viewRangeMS + t0; String str = formatClockTime(t); g.drawString(str, x, y + 16); // if (tickInterval > (1 * HOUR) && t % (1 * DAY) == 0) { if ((t + tz) % (1 * DAY) == 0) { str = formatDate(t); g.drawString(str, x, y + 27); } // Draw vertical grid line g.setColor(Color.lightGray); g.drawLine(x, topMargin, x, topMargin + h); g.setColor(fg); t0 += tickInterval; } // Plot values int start = 0; int nValues = 0; int nLists = seqs.size(); if (nLists > 0) { nValues = seqs.get(0).size; } if (nValues == 0) { g.setColor(oldColor); return; } else { Sequence seq = seqs.get(0); // Find starting point for (int p = 0; p < seq.size; p++) { if (times.time(p) >= tMax - viewRangeMS) { start = p; break; } } } // Optimization: collapse plot of more than four values per pixel int pointsPerPixel = (nValues - start) / w; if (pointsPerPixel < 4) { pointsPerPixel = 1; } // Draw graphs // Loop backwards over sequences because the first needs to be painted on top for (int i = nLists - 1; i >= 0; i--) { int x0 = leftMargin; int y0 = topMargin + h + 1; Sequence seq = seqs.get(i); if (seq.isPlotted && seq.size > 0) { // Paint twice, with white and with color for (int pass = 0; pass < 2; pass++) { g.setColor((pass == 0) ? Color.white : seq.color); int x1 = -1; long v1 = -1; for (int p = start; p < nValues; p += pointsPerPixel) { // Make sure we get the last value if (pointsPerPixel > 1 && p >= nValues - pointsPerPixel) { p = nValues - 1; } int x2 = (int) (w * (times.time(p) - (t1 - viewRangeMS)) / viewRangeMS); long v2 = seq.value(p); if (v2 >= vMin && v2 <= vMax) { int y2 = (int) (h * (v2 - vMin) / (vMax - vMin)); if (x1 >= 0 && v1 >= vMin && v1 <= vMax) { int y1 = (int) (h * (v1 - vMin) / (vMax - vMin)); if (y1 == y2) { // fillrect is much faster g.fillRect(x0 + x1, y0 - y1 - pass, x2 - x1, 1); } else { Graphics2D g2d = (Graphics2D) g; Stroke oldStroke = null; if (seq.transitionStroke != null) { oldStroke = g2d.getStroke(); g2d.setStroke(seq.transitionStroke); } g.drawLine(x0 + x1, y0 - y1 - pass, x0 + x2, y0 - y2 - pass); if (oldStroke != null) { g2d.setStroke(oldStroke); } } } } x1 = x2; v1 = v2; } } // Current value long v = seq.value(seq.size - 1); if (v >= vMin && v <= vMax) { if (bgIsLight) { g.setColor(seq.color); } else { g.setColor(fg); } x = r.x + r.width + 2; y = topMargin + h - (int) (h * (v - vMin) / (vMax - vMin)); // a small triangle/arrow g.fillPolygon(new int[] {x + 2, x + 6, x + 6}, new int[] {y, y + 3, y - 3}, 3); } g.setColor(fg); } } int[] valueStringSlots = new int[nLists]; for (int i = 0; i < nLists; i++) valueStringSlots[i] = -1; for (int i = 0; i < nLists; i++) { Sequence seq = seqs.get(i); if (seq.isPlotted && seq.size > 0) { // Draw current value // TODO: collapse values if pointsPerPixel >= 4 long v = seq.value(seq.size - 1); if (v >= vMin && v <= vMax) { x = r.x + r.width + 2; y = topMargin + h - (int) (h * (v - vMin) / (vMax - vMin)); int y2 = getValueStringSlot(valueStringSlots, y, 2 * 10, i); g.setFont(smallFont); if (bgIsLight) { g.setColor(seq.color); } else { g.setColor(fg); } String curValue = getFormattedValue(v, true); if (unit == Unit.PERCENT) { curValue += "%"; } int valWidth = fm.stringWidth(curValue); String legend = (displayLegend ? seq.name : ""); int legendWidth = fm.stringWidth(legend); if (checkRightMargin(valWidth) || checkRightMargin(legendWidth)) { // Wait for next repaint return; } g.drawString(legend, x + 17, Math.min(topMargin + h, y2 + 3 - 10)); g.drawString(curValue, x + 17, Math.min(topMargin + h + 10, y2 + 3)); // Maybe draw a short line to value if (y2 > y + 3) { g.drawLine(x + 9, y + 2, x + 14, y2); } else if (y2 < y - 3) { g.drawLine(x + 9, y - 2, x + 14, y2); } } g.setFont(oldFont); g.setColor(fg); } } g.setColor(oldColor); }
protected void finalize() throws Throwable { destroy(); super.finalize(); }
/** * The constructor for this class has a bunch of arguments: The frame argument is required for all * printing in Java. The jobname appears left justified at the top of each printed page. The font * size is specified in points, as on-screen font sizes are. The margins are specified in inches * (or fractions of inches). */ public HardcopyWriter( Frame frame, String jobname, int fontsize, double leftmargin, double rightmargin, double topmargin, double bottommargin) throws HardcopyWriter.PrintCanceledException { // Get the PrintJob object with which we'll do all the printing. // The call is synchronized on the static printprops object, which // means that only one print dialog can be popped up at a time. // If the user clicks Cancel in the print dialog, throw an exception. Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame synchronized (printprops) { job = toolkit.getPrintJob(frame, jobname, printprops); } if (job == null) throw new PrintCanceledException("User cancelled print request"); pagesize = job.getPageDimension(); // query the page size pagedpi = job.getPageResolution(); // query the page resolution // Bug Workaround: // On windows, getPageDimension() and getPageResolution don't work, so // we've got to fake them. if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) { // Use screen dpi, which is what the PrintJob tries to emulate, anyway pagedpi = toolkit.getScreenResolution(); System.out.println(pagedpi); // Assume a 8.5" x 11" page size. A4 paper users have to change this. pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi); System.out.println(pagesize); // We also have to adjust the fontsize. It is specified in points, // (1 point = 1/72 of an inch) but Windows measures it in pixels. fontsize = fontsize * pagedpi / 72; System.out.println(fontsize); System.out.flush(); } // Compute coordinates of the upper-left corner of the page. // I.e. the coordinates of (leftmargin, topmargin). Also compute // the width and height inside of the margins. x0 = (int) (leftmargin * pagedpi); y0 = (int) (topmargin * pagedpi); width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi); height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi); // Get body font and font size font = new Font("Monospaced", Font.PLAIN, fontsize); metrics = toolkit.getFontMetrics(font); lineheight = metrics.getHeight(); lineascent = metrics.getAscent(); charwidth = metrics.charWidth('0'); // Assumes a monospaced font! // Now compute columns and lines will fit inside the margins chars_per_line = width / charwidth; lines_per_page = height / lineheight; // Get header font information // And compute baseline of page header: 1/8" above the top margin headerfont = new Font("SansSerif", Font.ITALIC, fontsize); headermetrics = toolkit.getFontMetrics(headerfont); headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent(); // Compute the date/time string to display in the page header DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); df.setTimeZone(TimeZone.getDefault()); time = df.format(new Date()); this.jobname = jobname; // save name this.fontsize = fontsize; // save font size }
protected void finalize() throws Throwable { pDestroyFont(nativeFont); super.finalize(); }
private int getFontHeight() { return fmRef.getHeight(); }
private int getTextWidth(String text) { return fmRef.stringWidth(text); }