private void doCurrentMethodStep() {
   switch (type) {
     case 0: // bisectiei
       if (Math.abs(function.evaluate((Cn.lastElement()).x)) < err) {
         complete = true;
         theTimer.stop();
       } else if (function.evaluate((An.lastElement()).x) * function.evaluate((Cn.lastElement()).x)
           < 0) {
         Bn.add(Cn.lastElement());
         Cn.add(new PointDP(((An.lastElement()).x + (Bn.lastElement()).x) / 2, 0.0));
       } else {
         An.add(Cn.lastElement());
         Cn.add(new PointDP(((An.lastElement()).x + (Bn.lastElement()).x) / 2, 0.0));
       }
       break;
     case 1: // coardei
       {
         double evn = function.evaluate((An.lastElement()).x);
         if (Math.abs(evn) < err) {
           complete = true;
           theTimer.stop();
         } else {
           double ev0 = function.evaluate((An.firstElement()).x);
           double newVal = (An.firstElement().x * evn - An.lastElement().x * ev0) / (evn - ev0);
           An.add(new PointDP(newVal, 0.0));
         }
       }
       break;
     case 2: // secantei
       {
         double exn = function.evaluate((An.lastElement()).x);
         if (Math.abs(exn) < err) {
           complete = true;
           theTimer.stop();
         } else {
           double exn1 = function.evaluate((An.elementAt(An.size() - 2)).x);
           double newVal =
               (An.elementAt(An.size() - 2).x * exn - (An.lastElement()).x * exn1) / (exn - exn1);
           An.add(new PointDP(newVal, 0.0));
         }
       }
       break;
     case 3: // newton
       double xn = An.lastElement().x;
       if (Math.abs(function.evaluate(xn)) < err) {
         complete = true;
         theTimer.stop();
       }
       An.add(new PointDP(xn - function.evaluate(xn) / function.evaluate_1(xn), 0.0));
       break;
   }
 }
Beispiel #2
0
  public void mouseClicked(MouseEvent e) {
    int x;
    int y;

    e.consume();

    if (mouseEventsEnabled) {

      x = Math.round(e.getX() / scale);
      y = Math.round(e.getY() / scale);

      // allow for the canvas margin
      y -= margin;

      // System.out.println("Mouse Click: (" + x + ", " + y + ")");

      if (e.getClickCount() < 2) {
        if (nativeSelectItem(x, y)) {
          parentFTAFrame.updateFrame();
        }
      } else {
        if (nativeSelectItem(x, y)) {
          parentFTAFrame.updateFrame();
        }

        editSelected();
        parentFTAFrame.updateFrame();
      }

      if (focusEventsEnabled) {
        // tell the main Canvas to point to this coordinate
        parentFTAFrame.setCanvasFocus(x, y);
      }
    }
  }
Beispiel #3
0
  /**
   * Damages the area surrounding the caret to cause it to be repainted in a new location. If
   * paint() is reimplemented, this method should also be reimplemented. This method should update
   * the caret bounds (x, y, width, and height).
   *
   * @param r the current location of the caret
   * @see #paint
   */
  @Override
  protected synchronized void damage(final Rectangle r) {
    if (r == null || fPainting) return;

    x = r.x - 4;
    y = r.y;
    width = 10;
    height = r.height;

    // Don't damage the border area.  We can't paint a partial border, so get the
    // intersection of the caret rectangle and the component less the border, if any.
    final Rectangle caretRect = new Rectangle(x, y, width, height);
    final Border border = getComponent().getBorder();
    if (border != null) {
      final Rectangle alloc = getComponent().getBounds();
      alloc.x = alloc.y = 0;
      final Insets borderInsets = border.getBorderInsets(getComponent());
      alloc.x += borderInsets.left;
      alloc.y += borderInsets.top;
      alloc.width -= borderInsets.left + borderInsets.right;
      alloc.height -= borderInsets.top + borderInsets.bottom;
      Rectangle2D.intersect(caretRect, alloc, caretRect);
    }
    x = caretRect.x;
    y = caretRect.y;
    width = Math.max(caretRect.width, 1);
    height = Math.max(caretRect.height, 1);
    repaint();
  }
Beispiel #4
0
 /**
  * Returns the <sup>10</sup>log() of a value
  *
  * @return the <sup>10</sup>log()
  */
 static double log10(int v) {
   double dl = 0.0;
   if (v != 0.0) {
     dl = Math.log(v) / Math.log(10);
   }
   return dl;
 }
Beispiel #5
0
 private long normalizeMax(long l) {
   int exp = (int) Math.log10((double) l);
   long multiple = (long) Math.pow(10.0, exp);
   int i = (int) (l / multiple);
   l = (i + 1) * multiple;
   return l;
 }
 public void nudge(int i) {
   x[i] += (double) rand.nextInt(1000) / 8756;
   y[i] += (double) rand.nextInt(1000) / 5432;
   int tmpScale = (int) (Math.abs(Math.sin(x[i])) * 10);
   scale[i] = (double) tmpScale / 10;
   int nudgeX = (int) (((double) getWidth() / 2) * .8);
   int nudgeY = (int) (((double) getHeight() / 2) * .60);
   xh[i] = (int) (Math.sin(x[i]) * nudgeX) + nudgeX;
   yh[i] = (int) (Math.sin(y[i]) * nudgeY) + nudgeY;
 }
Beispiel #7
0
  private boolean buildNoteSequence() {

    noteSequence = new NoteSequence();

    double quantizeBeatFactor = quantizeBeatSetting * 1000.0 * 60.0 / (double) getBPM();
    double quantizeDurationFactor = quantizeDurationSetting * 1000.0 * 60.0 / (double) getBPM();

    for (int i = 0; i < noteList.size(); i++) {
      noteListElement = noteList.get(i);

      if (noteListElement.underTone == true) {
        continue;
      }

      note = noteListElement.note;

      if (note < getLowPitch()) continue;
      if (note > getHighPitch()) continue;

      double startTime = (double) (noteListElement.startTime);

      if (quantizeBeatFactor != 0.0)
        startTime = Math.floor(startTime / quantizeBeatFactor) * quantizeBeatFactor;
      long startTick = 1 + (long) (startTime * getTickRate() / 1000.0);

      double endTime = (double) (noteListElement.endTime);

      if (quantizeBeatFactor != 0.0)
        endTime = Math.ceil(endTime / quantizeBeatFactor) * quantizeBeatFactor;
      if (quantizeDurationFactor != 0)
        endTime =
            startTime
                + (Math.ceil((endTime - startTime) / quantizeDurationFactor)
                    * quantizeDurationFactor);

      long endTick = 1 + (long) (endTime * getTickRate() / 1000.0);

      if ((endTick - startTick) < 1) endTick = startTick + 1;
      System.out.println(
          "times: " + startTime + ", " + endTime + ", " + getStartTime() + ", " + getEndTime());
      if (endTime < getStartTime()) continue;
      if (startTime > getEndTime()) continue;

      velocity = 64;
      noteSequence.add(new NoteSequenceElement(note, ON, startTick, velocity));
      noteSequence.add(new NoteSequenceElement(note, OFF, endTick, velocity));
    }

    if (noteSequence.size() == 0) {
      return false;
    } else {
      noteSequence.sort();
      return true;
    }
  }
Beispiel #8
0
  public boolean transform(ProgressListener progressListener) {

    toneMap = toneMapFrame.getToneMap();
    timeSet = toneMap.getTimeSet();
    pitchSet = toneMap.getPitchSet();
    timeRange = timeSet.getRange();
    pitchRange = pitchSet.getRange();

    pitchFreqSet = pitchSet.getFreqSet();
    audioFTPower = new double[timeRange * (pitchRange + 1)];

    int startSample = timeSet.getStartSample();
    int endSample = timeSet.getEndSample();
    int sampleLength = (int) Math.floor((endSample - startSample) / ((double) resolution));
    double[] audioSamples = new double[sampleLength];

    for (int i = 0; i < sampleLength; i++) {
      audioSamples[i] = (double) audioData[startSample + i * resolution];
    }

    int sampleIndexSize =
        (int) Math.floor((double) timeSet.getSampleIndexSize() / (double) resolution);

    double dt = (double) resolution / sampleRate;
    if (transformMode == TRANSFORM_MODE_JAVA) {
      wavelet.convert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    } else {

      WaveletJNI waveletJNI = new WaveletJNI();

      waveletJNI.waveletConvert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    }

    return true;
  }
 private static Color getColorFromPallet(int[] pallet, float x) {
   if (x < 0f || x > 1f) {
     throw new IllegalArgumentException("Parameter outside of expected range");
   }
   int i = (int) (pallet.length * x);
   int max = pallet.length - 1;
   int index = Math.min(Math.max(i, 0), max);
   return new Color(pallet[index] & 0x00FFFFFF);
   // translucent
   // int pix = pallet[index] & 0x00FFFFFF | (0x64 << 24);
   // return new Color(pix), true);
 }
    protected void updateStatus() {
      // Update description
      String text = thread.getRetrievable().getName();
      text = text.length() > 30 ? text.substring(0, 27) + "..." : text;
      text +=
          " ("
              + BulkDownloadPanel.makeSizeDescription(this.progress.getCurrentSize())
              + " / "
              + BulkDownloadPanel.makeSizeDescription(this.progress.getTotalSize())
              + ")";
      this.descriptionLabel.setText(text);
      // Update progress bar
      int percent = 0;
      if (this.progress.getTotalCount() > 0)
        percent =
            (int) ((float) this.progress.getCurrentCount() / this.progress.getTotalCount() * 100f);
      this.progressBar.setValue(Math.min(percent, 100));
      // Update tooltip
      String tooltip = BulkDownloadPanel.makeSectorDescription(this.thread.getSector());
      this.descriptionLabel.setToolTipText(tooltip);
      this.progressBar.setToolTipText(makeProgressDescription());

      // Check for end of thread
      if (!this.thread.isAlive()) {
        // Thread is done
        this.cancelButton.setText("Remove");
        this.cancelButton.setBackground(Color.GREEN);
        this.updateTimer.stop();
      }
    }
  public Dimension getMinimumSize() {
    Dimension stereoDim = _stereo.getMinimumSize();
    Dimension nameDim = _name.getMinimumSize();

    int h = stereoDim.height + nameDim.height - OVERLAP;
    int w = Math.max(stereoDim.width, nameDim.width);
    return new Dimension(w, h);
  }
Beispiel #12
0
  public boolean play() {

    try {
      if (playState != STOPPED) playStop();

      if (audioBytes == null) return false;

      DataLine.Info info = new DataLine.Info(Clip.class, format);

      clip = (Clip) AudioSystem.getLine(info);
      clip.addLineListener(new ClipListener());

      long clipStart = (long) (audioBytes.length * getStartTime() / (getDuration() * 1000.0));
      long clipEnd = (long) (audioBytes.length * getEndTime() / (getDuration() * 1000.0));
      if ((clipEnd - clipStart) > MAX_CLIP_LENGTH) clipEnd = clipStart + MAX_CLIP_LENGTH;
      byte[] clipBytes = new byte[(int) (clipEnd - clipStart)];
      System.arraycopy(audioBytes, (int) clipStart, clipBytes, 0, clipBytes.length);
      clip.open(format, clipBytes, 0, clipBytes.length);

      FloatControl panControl = (FloatControl) clip.getControl(FloatControl.Type.PAN);

      panControl.setValue((float) panSetting / 100.0f);

      double value = (double) gainSetting;

      FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
      float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
      gainControl.setValue(dB);
      double playStartTime = (player.getSeekTime() / 100) * (playGetLength());
      clip.setMicrosecondPosition((long) playStartTime);

      clip.start();

      playState = PLAYING;

      return true;

    } catch (Exception ex) {
      ex.printStackTrace();
      playState = STOPPED;
      clip = null;
      return false;
    }
  }
  /*
   *  Adjust the width of the specified column in the table
   */
  public void adjustColumn(final int column) {
    TableColumn tableColumn = table.getColumnModel().getColumn(column);

    if (!tableColumn.getResizable()) return;

    int columnHeaderWidth = getColumnHeaderWidth(column);
    int columnDataWidth = getColumnDataWidth(column);
    int preferredWidth = Math.max(columnHeaderWidth, columnDataWidth);

    updateTableColumn(column, preferredWidth);
  }
Beispiel #14
0
 public int getHeight() {
   float fHeight;
   int height;
   fHeight = scale * nativeGetMaxDepth();
   height = Math.round(fHeight) + (2 * margin);
   if (parentContainer == null) {
     return height;
   } else {
     return FTAUtilities.max(height, parentContainer.getHeight());
   }
 }
Beispiel #15
0
 public int getWidth() {
   float fWidth;
   int width;
   fWidth = scale * nativeGetMaxWidth();
   width = Math.round(fWidth);
   if (parentContainer == null) {
     return width;
   } else {
     return FTAUtilities.max(width, parentContainer.getWidth());
   }
 }
Beispiel #16
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
  /*
   *  Calculate the width based on the widest cell renderer for the
   *  given column.
   */
  private int getColumnDataWidth(int column) {
    if (!isColumnDataIncluded) return 0;

    int preferredWidth = 0;
    int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();

    for (int row = 0; row < table.getRowCount(); row++) {
      preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));

      //  We've exceeded the maximum width, no need to check other rows

      if (preferredWidth >= maxWidth) break;
    }

    return preferredWidth;
  }
  /*
   *  Update the TableColumn with the newly calculated width
   */
  private void updateTableColumn(int column, int width) {
    final TableColumn tableColumn = table.getColumnModel().getColumn(column);

    if (!tableColumn.getResizable()) return;

    width += spacing;

    //  Don't shrink the column width

    if (isOnlyAdjustLarger) {
      width = Math.max(width, tableColumn.getPreferredWidth());
    }

    columnSizes.put(tableColumn, new Integer(tableColumn.getWidth()));
    table.getTableHeader().setResizingColumn(tableColumn);
    tableColumn.setWidth(width);
  }
Beispiel #19
0
 /**
  * Returns the minimum amount of space the layout needs.
  *
  * @param parent the Container for which this layout manager is being used
  * @return a Dimension object containing the layout's minimum size
  */
 public Dimension minimumLayoutSize(Container parent) {
   Dimension rd, mbd;
   Insets i = getInsets();
   if (contentPane != null) {
     rd = contentPane.getMinimumSize();
   } else {
     rd = parent.getSize();
   }
   if (menuBar != null && menuBar.isVisible()) {
     mbd = menuBar.getMinimumSize();
   } else {
     mbd = new Dimension(0, 0);
   }
   return new Dimension(
       Math.max(rd.width, mbd.width) + i.left + i.right,
       rd.height + mbd.height + i.top + i.bottom);
 }
Beispiel #20
0
  public boolean load(File file) {

    this.file = file;

    if (file != null && file.isFile()) {
      try {
        errStr = null;
        audioInputStream = AudioSystem.getAudioInputStream(file);

        fileName = file.getName();

        format = audioInputStream.getFormat();

      } catch (Exception ex) {
        reportStatus(ex.toString());
        return false;
      }
    } else {
      reportStatus("Audio file required.");
      return false;
    }

    numChannels = format.getChannels();
    sampleRate = (double) format.getSampleRate();
    sampleBitSize = format.getSampleSizeInBits();
    long frameLength = audioInputStream.getFrameLength();
    long milliseconds = (long) ((frameLength * 1000) / audioInputStream.getFormat().getFrameRate());
    double audioFileDuration = milliseconds / 1000.0;

    if (audioFileDuration > MAX_AUDIO_DURATION) duration = MAX_AUDIO_DURATION;
    else duration = audioFileDuration;

    frameLength = (int) Math.floor((duration / audioFileDuration) * (double) frameLength);

    try {
      audioBytes = new byte[(int) frameLength * format.getFrameSize()];
      audioInputStream.read(audioBytes);
    } catch (Exception ex) {
      reportStatus(ex.toString());
      return false;
    }

    getAudioData();

    return true;
  }
Beispiel #21
0
  /*
   *  Determine the Y offset for the current row
   */
  private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException {
    //  Get the bounding rectangle of the row

    Rectangle r = component.modelToView(rowStartOffset);
    int lineHeight = fontMetrics.getHeight();
    int y = r.y + r.height;
    int descent = 0;

    //  The text needs to be positioned above the bottom of the bounding
    //  rectangle based on the descent of the font(s) contained on the row.
    if (r.height == lineHeight) {
      // default font is being used
      descent = fontMetrics.getDescent();
    } else {
      // We need to check all the attributes for font changes
      if (fonts == null) {
        fonts = new HashMap<String, FontMetrics>();
      }

      Element root = component.getDocument().getDefaultRootElement();
      int index = root.getElementIndex(rowStartOffset);
      Element line = root.getElement(index);

      for (int i = 0; i < line.getElementCount(); i++) {
        Element child = line.getElement(i);
        AttributeSet as = child.getAttributes();
        String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
        Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
        String key = fontFamily + fontSize;

        FontMetrics fm = fonts.get(key);

        if (fm == null) {
          Font font = new Font(fontFamily, Font.PLAIN, fontSize);
          fm = component.getFontMetrics(font);
          fonts.put(key, fm);
        }

        descent = Math.max(descent, fm.getDescent());
      }
    }

    return y - descent;
  }
Beispiel #22
0
  /** Calculate the width needed to display the maximum line number */
  private void setPreferredWidth() {
    Element root = component.getDocument().getDefaultRootElement();
    int lines = root.getElementCount();
    int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits);

    //  Update sizes when number of digits in the line number changes
    if (lastDigits != digits) {
      lastDigits = digits;
      FontMetrics fontMetrics = getFontMetrics(getFont());
      int width = fontMetrics.charWidth('0') * digits;
      Insets insets = getInsets();
      int preferredWidth = insets.left + insets.right + width;

      Dimension d = getPreferredSize();
      d.setSize(preferredWidth, HEIGHT);
      setPreferredSize(d);
      setSize(d);
    }
  }
Beispiel #23
0
 /**
  * Returns the maximum amount of space the layout can use.
  *
  * @param target the Container for which this layout manager is being used
  * @return a Dimension object containing the layout's maximum size
  */
 public Dimension maximumLayoutSize(Container target) {
   Dimension rd, mbd;
   Insets i = getInsets();
   if (menuBar != null && menuBar.isVisible()) {
     mbd = menuBar.getMaximumSize();
   } else {
     mbd = new Dimension(0, 0);
   }
   if (contentPane != null) {
     rd = contentPane.getMaximumSize();
   } else {
     // This is silly, but should stop an overflow error
     rd =
         new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE - i.top - i.bottom - mbd.height - 1);
   }
   return new Dimension(
       Math.min(rd.width, mbd.width) + i.left + i.right,
       rd.height + mbd.height + i.top + i.bottom);
 }
Beispiel #24
0
  @Override
  protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    // Draw static content
    g2.setPaint(getBackground());
    frame(g2, cursorBox.x, cursorBox.y, cursorBox.width, cursorBox.height);
    frame(g2, zoomBox.x, zoomBox.y, zoomBox.width, zoomBox.height);
    frame(g2, selectionBox.x, selectionBox.y, selectionBox.width, selectionBox.height);

    Image image = State.getCurrentImage();
    if (image == null || cx == -1 || cy == -1) return;
    g2.setPaint(Color.BLACK);

    g2.drawString(
        getCursorAttributedString(image).getIterator(),
        textOffsetX(cursorBox),
        textOffsetY(cursorBox));

    g2.drawString(
        Math.round(image.getImagePanel().getZoom() * 100) + "%",
        textOffsetX(zoomBox),
        textOffsetY(zoomBox));
  }
Beispiel #25
0
  /** Get an image based on index numbers */
  public BufferedImage getIndexedImage(
      int x, int y, int zoom, int cacheZoom, GMapListener listener) {

    if (listener != null) {
      if (!getGDataSource().isCached(x, y, zoom)) {
        listener.updateGMapPainting();
        listener.updateGMapMessage(GMap.MESSAGE_DOWNLOADING);
      } else {
        listener.updateGMapMessage(GMap.MESSAGE_PAINTING);
      }
    }

    BufferedImage thumbImage = getGDataSource().getImage(x, y, zoom, true);

    if (thumbImage == null) return defaultImage;

    // if we dont have to paint cache, return here
    if (cacheZoom == (GPhysicalPoint.MIN_ZOOM - 1) || cacheZoom >= zoom) return thumbImage;

    BufferedImage paintedImage =
        new BufferedImage(
            GDataSource.sourceSize.width,
            GDataSource.sourceSize.height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics2D = paintedImage.createGraphics();
    graphics2D.drawImage(
        thumbImage, 0, 0, GDataSource.sourceSize.width, GDataSource.sourceSize.height, null);

    // now lets move to painting the cache
    double imageNum = Math.pow(2, zoom - cacheZoom);

    // draw cache lines
    int startX = (int) (imageNum * x);
    int startY = (int) (imageNum * y);

    // get composite to restore later, set new transparent composite
    Composite originalComposite = graphics2D.getComposite();
    graphics2D.setComposite(opacity40);

    // draw grid
    for (int i = 0; i < imageNum; i++) {
      for (int j = 0; j < imageNum; j++) {
        // points
        Point upperLeft =
            new Point(
                (int) (GDataSource.sourceSize.width / imageNum) * i,
                (int) (GDataSource.sourceSize.height / imageNum) * j);
        Dimension size =
            new Dimension(
                (int) (GDataSource.sourceSize.width / imageNum),
                (int) (GDataSource.sourceSize.height / imageNum));

        // draw lines
        graphics2D.setColor(new Color(100, 100, 100));
        graphics2D.drawLine(upperLeft.x, upperLeft.y, upperLeft.x + size.width, upperLeft.y);
        graphics2D.drawLine(upperLeft.x, upperLeft.y, upperLeft.x, upperLeft.y + size.height);

        // check if file exists
        if (getGDataSource().isCached(startX + i, startY + j, cacheZoom))
          graphics2D.setColor(Color.RED);
        else graphics2D.setColor(new Color(155, 155, 155));

        // shade rectangle
        graphics2D.fillRect(upperLeft.x, upperLeft.y, size.width, size.height);
      }
    }

    // restore composite
    graphics2D.setComposite(originalComposite);

    return paintedImage;
  }
Beispiel #26
0
 public void setDecimals(int decimals) {
   this.decimals = decimals;
   this.decimalsMultiplier = Math.pow(10.0, decimals);
 }
Beispiel #27
0
  private static class Sequence {
    String key;
    String name;
    Color color;
    boolean isPlotted;
    Stroke transitionStroke = null;

    // Values are stored in an int[] if all values will fit,
    // otherwise in a long[]. An int can represent up to 2 GB.
    // Use a random start size, so all arrays won't need to
    // be grown during the same update interval
    Object values = new byte[ARRAY_SIZE_INCREMENT + (int) (Math.random() * 100)];

    // Number of stored values
    int size = 0;

    public Sequence(String key) {
      this.key = key;
    }

    /** Returns the value at index i */
    public long value(int i) {
      return Array.getLong(values, i);
    }

    public void add(long value) {
      // May need to switch to a larger array type
      if ((values instanceof byte[] || values instanceof short[] || values instanceof int[])
          && value > Integer.MAX_VALUE) {
        long[] la = new long[Array.getLength(values)];
        for (int i = 0; i < size; i++) {
          la[i] = Array.getLong(values, i);
        }
        values = la;
      } else if ((values instanceof byte[] || values instanceof short[])
          && value > Short.MAX_VALUE) {
        int[] ia = new int[Array.getLength(values)];
        for (int i = 0; i < size; i++) {
          ia[i] = Array.getInt(values, i);
        }
        values = ia;
      } else if (values instanceof byte[] && value > Byte.MAX_VALUE) {
        short[] sa = new short[Array.getLength(values)];
        for (int i = 0; i < size; i++) {
          sa[i] = Array.getShort(values, i);
        }
        values = sa;
      }

      // May need to extend the array size
      if (Array.getLength(values) == size) {
        values = extendArray(values);
      }

      // Store the value
      if (values instanceof long[]) {
        ((long[]) values)[size] = value;
      } else if (values instanceof int[]) {
        ((int[]) values)[size] = (int) value;
      } else if (values instanceof short[]) {
        ((short[]) values)[size] = (short) value;
      } else {
        ((byte[]) values)[size] = (byte) value;
      }
      size++;
    }
  }
  // ----------------------------------------------------------------
  // FIT TO SCREEN
  // this function will set the scaling factors above such
  // that all nodes are scaled to within the screen viewing area
  public void FitToScreen() // do not synchronize
      {
    double largestXCoord = Double.MIN_VALUE;
    double smallestXCoord = Double.MAX_VALUE;
    double largestYCoord = Double.MIN_VALUE;
    double smallestYCoord = Double.MAX_VALUE;
    double x, y;
    // find the largest and smallest coords for all nodes
    DisplayManager.NodeInfo currentDisplayInfo;
    for (Enumeration nodes = MainClass.displayManager.GetNodeInfo(); nodes.hasMoreElements(); ) {
      currentDisplayInfo = (DisplayManager.NodeInfo) nodes.nextElement();
      if (screenIsEmpty) {
        currentDisplayInfo.SetFitOnScreen(true);
      }
      if (((currentDisplayInfo.GetDisplayThisNode() == true)
          && (currentDisplayInfo.GetFitOnScreen()
              == true))) // If the current node is displayed and old enough, or if they are the
      // first nodes to be drawn
      {
        x = MainClass.locationAnalyzer.GetX(currentDisplayInfo.GetNodeNumber());
        y = MainClass.locationAnalyzer.GetY(currentDisplayInfo.GetNodeNumber());
        if (x > largestXCoord) {
          largestXCoord = x;
        }
        if (x < smallestXCoord) {
          smallestXCoord = x;
        }
        if (y > largestYCoord) {
          largestYCoord = y;
        }
        if (y < smallestYCoord) {
          smallestYCoord = y;
        }
      }
    }
    // here we use the following equations to set the scaling factors:
    // xScale*SmallestXCoord + XIntercept = 0
    // xScale*LargestXCoord  + XIntercept = window.width();
    //
    // And the same for the y scaling factors.
    // Note that I want a border of <Margin>% of the screen on both sides

    Dimension d = getSize();

    xScale = (d.width - 2 * (d.width / xMargin)) / (largestXCoord - smallestXCoord);
    yScale = (d.height - 2 * (d.height / yMargin)) / (largestYCoord - smallestYCoord);

    xScale =
        Math.min(
            xScale, yScale); // this is to make sure that the x and y coordinates are not warped
    yScale = xScale;

    xScaleIntercept = -xScale * smallestXCoord + d.width / xMargin;
    yScaleIntercept = -yScale * smallestYCoord + d.height / yMargin;
    screenIsEmpty = false;
    if (MainClass.displayManager.proprietaryNodeInfo
        .isEmpty()) // if there are no nodes and none of this function was executed
    {
      screenIsEmpty = true;
      xScale = 1;
      yScale = 1;
      xScaleIntercept = 0;
      yScaleIntercept = 0;
    }
    // System.out.println(xScale + " " + yScale);
    // System.out.println(xScaleIntercept + " " + yScaleIntercept);
  }
  protected boolean exportApplicationPrompt() throws IOException, SketchException {
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(Box.createVerticalStrut(6));

    // Box panel = Box.createVerticalBox();

    // Box labelBox = Box.createHorizontalBox();
    //    String msg = "<html>Click Export to Application to create a standalone, " +
    //      "double-clickable application for the selected plaforms.";

    //    String msg = "Export to Application creates a standalone, \n" +
    //      "double-clickable application for the selected plaforms.";
    String line1 = "Export to Application creates double-clickable,";
    String line2 = "standalone applications for the selected plaforms.";
    JLabel label1 = new JLabel(line1, SwingConstants.CENTER);
    JLabel label2 = new JLabel(line2, SwingConstants.CENTER);
    label1.setAlignmentX(Component.LEFT_ALIGNMENT);
    label2.setAlignmentX(Component.LEFT_ALIGNMENT);
    //    label1.setAlignmentX();
    //    label2.setAlignmentX(0);
    panel.add(label1);
    panel.add(label2);
    int wide = label2.getPreferredSize().width;
    panel.add(Box.createVerticalStrut(12));

    final JCheckBox windowsButton = new JCheckBox("Windows");
    // windowsButton.setMnemonic(KeyEvent.VK_W);
    windowsButton.setSelected(Preferences.getBoolean("export.application.platform.windows"));
    windowsButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean(
                "export.application.platform.windows", windowsButton.isSelected());
          }
        });

    final JCheckBox macosxButton = new JCheckBox("Mac OS X");
    // macosxButton.setMnemonic(KeyEvent.VK_M);
    macosxButton.setSelected(Preferences.getBoolean("export.application.platform.macosx"));
    macosxButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean("export.application.platform.macosx", macosxButton.isSelected());
          }
        });

    final JCheckBox linuxButton = new JCheckBox("Linux");
    // linuxButton.setMnemonic(KeyEvent.VK_L);
    linuxButton.setSelected(Preferences.getBoolean("export.application.platform.linux"));
    linuxButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean("export.application.platform.linux", linuxButton.isSelected());
          }
        });

    JPanel platformPanel = new JPanel();
    // platformPanel.setLayout(new BoxLayout(platformPanel, BoxLayout.X_AXIS));
    platformPanel.add(windowsButton);
    platformPanel.add(Box.createHorizontalStrut(6));
    platformPanel.add(macosxButton);
    platformPanel.add(Box.createHorizontalStrut(6));
    platformPanel.add(linuxButton);
    platformPanel.setBorder(new TitledBorder("Platforms"));
    // Dimension goodIdea = new Dimension(wide, platformPanel.getPreferredSize().height);
    // platformPanel.setMaximumSize(goodIdea);
    wide = Math.max(wide, platformPanel.getPreferredSize().width);
    platformPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    panel.add(platformPanel);

    //  Box indentPanel = Box.createHorizontalBox();
    //  indentPanel.add(Box.createHorizontalStrut(new JCheckBox().getPreferredSize().width));
    final JCheckBox showStopButton = new JCheckBox("Show a Stop button");
    // showStopButton.setMnemonic(KeyEvent.VK_S);
    showStopButton.setSelected(Preferences.getBoolean("export.application.stop"));
    showStopButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            Preferences.setBoolean("export.application.stop", showStopButton.isSelected());
          }
        });
    showStopButton.setEnabled(Preferences.getBoolean("export.application.fullscreen"));
    showStopButton.setBorder(new EmptyBorder(3, 13, 6, 13));
    //  indentPanel.add(showStopButton);
    //  indentPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

    final JCheckBox fullScreenButton = new JCheckBox("Full Screen (Present mode)");
    // fullscreenButton.setMnemonic(KeyEvent.VK_F);
    fullScreenButton.setSelected(Preferences.getBoolean("export.application.fullscreen"));
    fullScreenButton.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            boolean sal = fullScreenButton.isSelected();
            Preferences.setBoolean("export.application.fullscreen", sal);
            showStopButton.setEnabled(sal);
          }
        });
    fullScreenButton.setBorder(new EmptyBorder(3, 13, 3, 13));

    JPanel optionPanel = new JPanel();
    optionPanel.setLayout(new BoxLayout(optionPanel, BoxLayout.Y_AXIS));
    optionPanel.add(fullScreenButton);
    optionPanel.add(showStopButton);
    //    optionPanel.add(indentPanel);
    optionPanel.setBorder(new TitledBorder("Options"));
    wide = Math.max(wide, platformPanel.getPreferredSize().width);
    // goodIdea = new Dimension(wide, optionPanel.getPreferredSize().height);
    optionPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    // optionPanel.setMaximumSize(goodIdea);
    panel.add(optionPanel);

    Dimension good;
    // label1, label2, platformPanel, optionPanel
    good = new Dimension(wide, label1.getPreferredSize().height);
    label1.setMaximumSize(good);
    good = new Dimension(wide, label2.getPreferredSize().height);
    label2.setMaximumSize(good);
    good = new Dimension(wide, platformPanel.getPreferredSize().height);
    platformPanel.setMaximumSize(good);
    good = new Dimension(wide, optionPanel.getPreferredSize().height);
    optionPanel.setMaximumSize(good);

    //    JPanel actionPanel = new JPanel();
    //    optionPanel.setLayout(new BoxLayout(optionPanel, BoxLayout.X_AXIS));
    //    optionPanel.add(Box.createHorizontalGlue());

    //    final JDialog frame = new JDialog(editor, "Export to Application");

    //    JButton cancelButton = new JButton("Cancel");
    //    cancelButton.addActionListener(new ActionListener() {
    //      public void actionPerformed(ActionEvent e) {
    //        frame.dispose();
    //        return false;
    //      }
    //    });

    // Add the buttons in platform-specific order
    //    if (PApplet.platform == PConstants.MACOSX) {
    //      optionPanel.add(cancelButton);
    //      optionPanel.add(exportButton);
    //    } else {
    //      optionPanel.add(exportButton);
    //      optionPanel.add(cancelButton);
    //    }
    String[] options = {"Export", "Cancel"};
    final JOptionPane optionPane =
        new JOptionPane(
            panel,
            JOptionPane.PLAIN_MESSAGE,
            // JOptionPane.QUESTION_MESSAGE,
            JOptionPane.YES_NO_OPTION,
            null,
            options,
            options[0]);

    final JDialog dialog = new JDialog(this, "Export Options", true);
    dialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (dialog.isVisible()
                && (e.getSource() == optionPane)
                && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
              // If you were going to check something
              // before closing the window, you'd do
              // it here.
              dialog.setVisible(false);
            }
          }
        });
    dialog.pack();
    dialog.setResizable(false);

    Rectangle bounds = getBounds();
    dialog.setLocation(
        bounds.x + (bounds.width - dialog.getSize().width) / 2,
        bounds.y + (bounds.height - dialog.getSize().height) / 2);
    dialog.setVisible(true);

    Object value = optionPane.getValue();
    if (value.equals(options[0])) {
      return jmode.handleExportApplication(sketch);
    } else if (value.equals(options[1]) || value.equals(new Integer(-1))) {
      // closed window by hitting Cancel or ESC
      statusNotice("Export to Application canceled.");
    }
    return false;
  }
Beispiel #30
0
  @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);
  }