예제 #1
1
  /**
   * 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)));
      }
    }
  }
예제 #2
0
파일: Clusters.java 프로젝트: arneboe/jplag
  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);
  }
예제 #3
0
  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);
    }
  }
예제 #4
0
  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;
  }
예제 #5
0
 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);
 }
예제 #6
0
    /** @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;
    }
예제 #7
0
 static void paintDropShadowText(
     final Graphics g,
     final JComponent c,
     final Font font,
     final FontMetrics metrics,
     final int x,
     final int y,
     final int offsetX,
     final int offsetY,
     final Color textColor,
     final Color shadowColor,
     final String text) {
   g.setFont(font);
   g.setColor(shadowColor);
   SwingUtilities2.drawString(c, g, text, x + offsetX, y + offsetY + metrics.getAscent());
   g.setColor(textColor);
   SwingUtilities2.drawString(c, g, text, x, y + metrics.getAscent());
 }
예제 #8
0
 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;
 }
예제 #9
0
 public Line render(String text, Color c) {
   text = Translate.get(text);
   Coord sz = strsize(text);
   if (sz.x < 1) sz = sz.add(1, 0);
   BufferedImage img = TexI.mkbuf(sz);
   Graphics g = img.createGraphics();
   if (aa) Utils.AA(g);
   g.setFont(font);
   g.setColor(c);
   FontMetrics m = g.getFontMetrics();
   g.drawString(text, 0, m.getAscent());
   g.dispose();
   return (new Line(text, img, m));
 }
예제 #10
0
  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;
  }
예제 #11
0
    /** @see prefuse.render.Renderer#render(java.awt.Graphics2D, prefuse.visual.VisualItem) */
    @Override
    public void render(Graphics2D g, VisualItem item) {
      Shape s = getShape(item);
      GraphicsLib.paint(g, item, m_line, getStroke(item), getRenderType(item));

      // check if we have a text label, if so, render it
      String str;
      if (item.canGetString(VisualItem.LABEL)) {
        str = (String) item.getString(VisualItem.LABEL);
        if (str != null && !str.equals("")) {
          float x = (float) m_box.getMinX();
          float y = (float) m_box.getMinY() + m_ascent;

          // draw label background
          GraphicsLib.paint(g, item, s, null, RENDER_TYPE_FILL);

          AffineTransform origTransform = g.getTransform();
          AffineTransform transform = this.getTransform(item);
          if (transform != null) {
            g.setTransform(transform);
          }

          g.setFont(item.getFont());
          g.setColor(ColorLib.getColor(item.getTextColor()));

          if (!(str.length() > 5
              && str.substring(str.length() - 5, str.length()).equals("_last"))) {

            g.setColor(Color.WHITE);
            // TODO properly hunt down source of null str! for now, triage
            if (str != null) {
              // bump y down by appropriate amount
              FontMetrics fm = g.getFontMetrics(item.getFont());
              int strHeight = fm.getAscent();
              //                        g.drawString(str, x, y);
              g.drawString(str, x, y + strHeight);
            }

            if (transform != null) {
              g.setTransform(origTransform);
            }
          }
        }
      }
    }
예제 #12
0
파일: set.java 프로젝트: wcyuan/Set
    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);
    }
예제 #13
0
  /**
   * 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
  }
  @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);
      }
    }
  }
  public void paintRegion(Graphics2D g, int x1, int y1, int w, int h) {
    int h2 = h / 2;
    int rad = 3;
    int diam = rad * 2;

    Color lg = Color.cyan;
    Color dg = Color.orange;

    lg = new Color(lg.getRed(), lg.getGreen(), lg.getBlue(), 75);
    dg = new Color(dg.getRed(), dg.getGreen(), dg.getBlue(), 75);

    /*
     * Draw the Baseline
     */
    g.setColor(Color.black);
    g.drawLine(x1, y1 + h, x1 + w, y1 + h);

    Stroke oldStroke = g.getStroke();
    g.setStroke(new BasicStroke((float) 2.0));

    /*
     * Draw the datapoints
     */
    for (ExprPoint ep : points) {
      if (ep.strand == '+') {
        g.setColor(lg);
      } else {
        g.setColor(dg);
      }

      g.drawOval(x1 + ep.x - rad, y1 + ep.y - rad, diam, diam);
    }

    g.setStroke(oldStroke);

    /*
     * Paint the hash marks...
     */
    if (!displayOppositeChannel) {
      g.setColor(Color.black);
      boolean flipper = true;
      for (int value = 100;
          value <= scale.getMax();
          value *= (flipper ? 5 : 2), flipper = !flipper) {
        int yoff = getYOffset((double) value);
        String line = String.format("%d", value);
        int uy = y1 + h2 - yoff, ly = y1 + h2 + yoff;

        g.drawLine(x1, uy, x1 + 10, uy);
        g.drawString(line, x1 + 12, uy + 5);

        g.drawLine(x1, ly, x1 + 10, ly);
        g.drawString(line, x1 + 12, ly + 5);
      }
    }

    /*
     * Draw any selections.
     */

    g.setColor(Color.black);
    for (Point p : selections.keySet()) {
      ExprPoint ep = selections.get(p);
      g.drawLine(p.x, p.y, ep.x, ep.y);
      g.drawString(ep.getLabel(), p.x, p.y);
    }

    /*
     * Draw the label in the upper-right hand corner.
     */
    g.setColor(Color.black);
    Font oldFont = g.getFont();
    Font newFont = new Font("Arial", Font.BOLD, 24);
    g.setFont(newFont);
    FontMetrics fm = g.getFontMetrics();
    int lblHeight = fm.getAscent() + fm.getDescent();
    int lblWidth = fm.charsWidth(label.toCharArray(), 0, label.length());

    int padding = 5;
    int lblx = x1 + w - lblWidth - padding;
    int lbly = y1 + lblHeight + padding;

    g.drawString(label, lblx, lbly);

    g.setFont(oldFont);
  }
예제 #16
0
 public Coord base() {
   return (new Coord(0, m.getAscent()));
 }
예제 #17
0
  /**
   * 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);
    }
  }
예제 #18
0
  /** 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;
    }
  }
예제 #19
0
 public int height() {
   /* XXX: Should leading go into this, when it's mostly
    * supposed to be used for one-liners? */
   return (m.getAscent() + m.getDescent());
 }