Пример #1
0
  public ExtendedTextField() {
    setFullScreenMode(true);

    setCommandListener(this);

    exit = new Command("Exit", Command.EXIT, 1);
    open = new Command("Open", Command.ITEM, 1);
    newFile = new Command("New", Command.ITEM, 2);
    save = new Command("Save", Command.ITEM, 3);
    saveAs = new Command("Save As", Command.ITEM, 4);
    eval = new Command("Eval", Command.ITEM, 5);
    output = new Command("Output", Command.ITEM, 6);
    cls = new Command("Clear", Command.ITEM, 7);

    addCommand(exit);
    addCommand(newFile);
    addCommand(open);
    addCommand(save);
    addCommand(saveAs);
    addCommand(eval);
    addCommand(output);
    addCommand(cls);

    new Thread(this).start();

    // TODO: change font size?
    inputFont = Font.getDefaultFont();
    inputWidth = getWidth();
    inputHeight = inputFont.getHeight();
    linesOnScreen = getHeight() / inputHeight;

    addNewLine(0);
  }
Пример #2
0
 /** @see Object#toString() */
 public String toString() {
   return "[Font Data face='"
       + getName()
       + "' size="
       + size
       + " bold="
       + javaFont.isBold()
       + " italic="
       + javaFont.isItalic()
       + "]";
 }
Пример #3
0
  public Container CreateContentPane() {
    // Create the content-pane-to-be.
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setOpaque(true);

    // the log panel
    log = new JTextPane();
    log.setEditable(false);
    log.setBackground(Color.BLACK);
    logPane = new JScrollPane(log);
    kit = new HTMLEditorKit();
    doc = new HTMLDocument();
    log.setEditorKit(kit);
    log.setDocument(doc);
    DefaultCaret c = (DefaultCaret) log.getCaret();
    c.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    ClearLog();

    // the preview panel
    previewPane = new DrawPanel();
    previewPane.setPaperSize(paper_top, paper_bottom, paper_left, paper_right);

    // status bar
    statusBar = new StatusBar();
    Font f = statusBar.getFont();
    statusBar.setFont(f.deriveFont(Font.BOLD, 15));
    Dimension d = statusBar.getMinimumSize();
    d.setSize(d.getWidth(), d.getHeight() + 30);
    statusBar.setMinimumSize(d);

    // layout
    Splitter split = new Splitter(JSplitPane.VERTICAL_SPLIT);
    split.add(previewPane);
    split.add(logPane);
    split.setDividerSize(8);

    contentPane.add(statusBar, BorderLayout.SOUTH);
    contentPane.add(split, BorderLayout.CENTER);

    // open the file
    if (recentFiles[0].length() > 0) {
      OpenFileOnDemand(recentFiles[0]);
    }

    // connect to the last port
    ListSerialPorts();
    if (Arrays.asList(portsDetected).contains(recentPort)) {
      OpenPort(recentPort);
    }

    return contentPane;
  }
Пример #4
0
  /**
   * Create a new font data element
   *
   * @param ttf The TTF file to read
   * @param size The size of the new font
   * @throws java.io.IOException Indicates a failure to
   */
  private FontData(InputStream ttf, float size) throws IOException {
    if (ttf.available() > MAX_FILE_SIZE) {
      throw new IOException("Can't load font - too big");
    }
    byte[] data = IOUtils.toByteArray(ttf);
    if (data.length > MAX_FILE_SIZE) {
      throw new IOException("Can't load font - too big");
    }

    this.size = size;
    try {
      javaFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(data));
      TTFFile rawFont = new TTFFile();
      if (!rawFont.readFont(new FontFileReader(data))) {
        throw new IOException("Invalid font file");
      }
      upem = rawFont.getUPEM();
      ansiKerning = rawFont.getAnsiKerning();
      charWidth = rawFont.getAnsiWidth();
      fontName = rawFont.getPostScriptName();
      familyName = rawFont.getFamilyName();

      String name = getName();
      System.err.println("Loaded: " + name + " (" + data.length + ")");
      boolean bo = false;
      boolean it = false;
      if (name.indexOf(',') >= 0) {
        name = name.substring(name.indexOf(','));

        if (name.indexOf("Bold") >= 0) {
          bo = true;
        }
        if (name.indexOf("Italic") >= 0) {
          it = true;
        }
      }

      if ((bo & it)) {
        javaFont = javaFont.deriveFont(Font.BOLD | Font.ITALIC);
      } else if (bo) {
        javaFont = javaFont.deriveFont(Font.BOLD);
      } else if (it) {
        javaFont = javaFont.deriveFont(Font.ITALIC);
      }
    } catch (FontFormatException e) {
      IOException x = new IOException("Failed to read font");
      x.initCause(e);
      throw x;
    }
  }
  /**
   * Gets the FontMetrics object for the supplied font. This method caches font metrics to ensure
   * native fonts are not loaded twice for the same font.
   */
  static synchronized QtFontMetrics getFontMetrics(Font font, boolean backwardCompat) {

    /* See if metrics has been stored in font already. */

    QtFontMetrics fm = (QtFontMetrics) font.metrics;

    if (fm == null) {
      boolean strikethrough = false, underline = false;

      /* See if a font metrics of the same native name and size has already been loaded.
      If it has then we use that one. */

      String nativeName = (String) fontNameMap.get(font.name.toLowerCase());

      if (nativeName == null) nativeName = (String) fontNameMap.get("default");

      String key = nativeName + "." + font.style + "." + font.size;

      if (!backwardCompat) {
        Map fa = font.getAttributes();
        Object obj;

        if ((obj = fa.get(TextAttribute.STRIKETHROUGH)) != null) {
          if (obj.equals(TextAttribute.STRIKETHROUGH_ON)) {
            key += ".s";
            strikethrough = true;
          }
        }

        if ((obj = fa.get(TextAttribute.UNDERLINE)) != null) {
          if (obj.equals(TextAttribute.UNDERLINE_ON)) {
            key += ".u";
            underline = true;
          }
        }
      }

      fm = (QtFontMetrics) fontMetricsMap.get(key);

      if (fm == null) {
        fontMetricsMap.put(
            key, fm = new QtFontMetrics(font, nativeName, font.style, strikethrough, underline));
      }

      font.metrics = fm;
    }

    return fm;
  }
Пример #6
0
 public static void saveImageResultsToPng(String prefix, ImageSearchHits hits, String queryImage)
     throws IOException {
   LinkedList<BufferedImage> results = new LinkedList<BufferedImage>();
   int width = 0;
   for (int i = 0; i < hits.length(); i++) {
     // hits.score(i)
     // hits.doc(i).get("descriptorImageIdentifier")
     BufferedImage tmp =
         ImageIO.read(new FileInputStream(hits.doc(i).get("descriptorImageIdentifier")));
     //            if (tmp.getHeight() > 200) {
     double factor = 200d / ((double) tmp.getHeight());
     tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200);
     //            }
     width += tmp.getWidth() + 5;
     results.add(tmp);
   }
   BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2 = (Graphics2D) result.getGraphics();
   g2.setColor(Color.white);
   g2.setBackground(Color.white);
   g2.clearRect(0, 0, result.getWidth(), result.getHeight());
   g2.setColor(Color.black);
   g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12"));
   int offset = 0;
   int count = 0;
   for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext(); ) {
     BufferedImage next = iterator.next();
     g2.drawImage(next, offset, 20, null);
     g2.drawString(hits.score(count) + "", offset + 5, 12);
     offset += next.getWidth() + 5;
     count++;
   }
   ImageIO.write(
       result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png"));
 }
Пример #7
0
  private void addFont(String fontKey, String fontName, float scale) {
    try {
      fontName = fontName.toLowerCase();

      FileInputStream stream = new FileInputStream("data/fonts/ttf/" + fontName + ".ttf");

      Font f = Font.createFont(Font.TRUETYPE_FONT, stream);
      f = f.deriveFont(scale);

      fonts.put(fontKey, f);
      stream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #8
0
  void displayCharacterMap(Graphics g) {
    if (currentChars != null) {
      g.setColor(0xffffff);
      g.fillRect(0, getHeight() - inputHeight - 2, getWidth(), inputHeight + 2);
      g.setColor(0x000000);
      g.drawLine(0, getHeight() - inputHeight - 2, getWidth(), getHeight() - inputHeight - 2);
      for (int i = 0; i < currentChars.length; i++) {
        char ch = currentChars[i];
        if (isUppercase) {
          ch = String.valueOf(currentChars[i]).toUpperCase().charAt(0);
        }

        // TODO: if i*12 > getWidth() ?

        g.drawChar(ch, i * 12, getHeight() - inputHeight, Graphics.LEFT | Graphics.TOP);
        if (currentChars[currentKeyStep] == currentChars[i]) {
          g.drawRect(
              i * 12 - 2,
              getHeight() - inputHeight - 2,
              inputFont.charWidth(ch) + 4,
              inputHeight + 4);
        }
      }
    }
  }
Пример #9
0
  /**
   * Loads a font based on file path
   *
   * @param String filePath
   * @param float fontSize
   * @param FontStyle fontStyle
   * @throws FontFormatException
   * @throws IOException
   */
  public INFont(String filePath, float fontSize, FontStyle fontStyle)
      throws FontFormatException, IOException {
    File fontFile = new File(filePath);

    this.loadedFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);
    this.loadedFont = this.loadedFont.deriveFont(fontSize);

    this.style = fontStyle;
    this.size = fontSize;

    switch (fontStyle) {
      case BOLD:
        this.loadedFont = this.loadedFont.deriveFont(Font.BOLD);
        break;
      case ITALIC:
        this.loadedFont = this.loadedFont.deriveFont(Font.ITALIC);
        break;
      case PLAIN:
        this.loadedFont = this.loadedFont.deriveFont(Font.PLAIN);
        break;
      case BOLDANDITALIC:
        this.loadedFont = this.loadedFont.deriveFont(Font.BOLD + Font.ITALIC);
        break;
    }
  }
Пример #10
0
  /**
   * Set current font. Default to Plain Courier 11 if null.
   *
   * @param font new font.
   */
  public void setFont(Font font) {

    if (font != null) {
      m_localGraphicsState.setFont(font);
      if (font.getName().equals(m_psGraphicsState.getFont().getName())
          && (m_psGraphicsState.getFont().getStyle() == font.getStyle())
          && (m_psGraphicsState.getFont().getSize() == yScale(font.getSize()))) return;
      m_psGraphicsState.setFont(
          new Font(font.getName(), font.getStyle(), yScale(getFont().getSize())));
    } else {
      m_localGraphicsState.setFont(new Font("Courier", Font.PLAIN, 11));
      m_psGraphicsState.setFont(getFont());
    }

    m_printstream.println("/(" + replacePSFont(getFont().getPSName()) + ")" + " findfont");
    m_printstream.println(yScale(getFont().getSize()) + " scalefont setfont");
  }
Пример #11
0
 /**
  * Gets the BDFontMetrics object for the supplied font. This method caches font metrics to ensure
  * native fonts are not loaded twice for the same font.
  */
 static synchronized BDFontMetrics getFontMetrics(Font font) {
   /* See if metrics has been stored in font already. */
   BDFontMetrics fm = null;
   // BDFontMetrics fm = (BDFontMetrics)font.metrics;
   // if (fm == null) {
   /* See if a font metrics of the same native name and size has already been loaded.
   If it has then we use that one. */
   String nativeName =
       (String) fontNameMap.get(font.getName().toLowerCase() + "." + font.getStyle());
   if (nativeName == null) nativeName = (String) fontNameMap.get("default." + font.getStyle());
   String key = nativeName + "." + font.getSize();
   fm = (BDFontMetrics) fontMetricsMap.get(key);
   if (fm == null) fontMetricsMap.put(key, fm = new BDFontMetrics(font, nativeName));
   // font.metrics = fm;
   // }
   return fm;
 }
Пример #12
0
  void displayLines(Graphics g, int yStart) {
    // (1 + 2, depends on font size)

    if (isSelection && (xStartSelection != xEndSelection || yStartSelection != yEndSelection)) {
      for (int y = Math.max(0, yStart);
          y < Math.min(yStart + linesOnScreen + 1 + 2, vectorLines.size());
          y++) {
        String currentLine = vectorLines.elementAt(y).toString();
        int width = 0;

        for (int x = 0; x < currentLine.length(); x++) {
          int previousWidth = (x == 0) ? 0 : inputFont.charWidth(currentLine.charAt(x - 1));
          width += previousWidth;

          if (isSelected(x, y)) {
            g.setColor(0x000000);
            g.fillRect(
                width, y * inputHeight, inputFont.charWidth(currentLine.charAt(x)), inputHeight);

            g.setColor(0xffffff);
            g.drawChar(currentLine.charAt(x), width, y * inputHeight, Graphics.LEFT | Graphics.TOP);
          } else {
            g.setColor(0x000000);
            g.drawChar(currentLine.charAt(x), width, y * inputHeight, Graphics.LEFT | Graphics.TOP);
          }
        }

        if (currentLine.length() == 0) {
          if (isSelected(0, y)) {
            g.setColor(0x000000);
            g.fillRect(0, y * inputHeight, 5, inputHeight);
          }
        }
      }
    } else {
      for (int y = Math.max(0, yStart);
          y < Math.min(yStart + linesOnScreen + 1 + 2, vectorLines.size());
          y++) {
        g.drawString(
            vectorLines.elementAt(y).toString(), 0, y * inputHeight, Graphics.LEFT | Graphics.TOP);
      }
    }
  }
Пример #13
0
 public void adjustFont(int w, int h) {
   if (h <= 0) return;
   int oldH = rHeight;
   if (font == null) {
     font = getFont();
     fontH = font.getSize();
     rHeight = fontH;
   }
   nHeight = h;
   if (fontH >= h) rHeight = h - 2;
   else rHeight = fontH;
   if ((rHeight < 10) && (fontH > 10)) rHeight = 10;
   if (oldH != rHeight) {
     // Font  curFont = font.deriveFont((float) rHeight);
     Font curFont = DisplayOptions.getFont(font.getName(), font.getStyle(), rHeight);
     setFont(curFont);
   }
   if (rHeight > h) rHeight = h;
 }
Пример #14
0
  /**
   * Creates a font metrics for the supplied font. To get a font metrics for a font use the static
   * method getFontMetrics instead which does caching.
   */
  private BDFontMetrics(Font font, String nativeName) {
    super(font);

    ftFace = loadFontN(ftLib, nativeName, font.getSize());
    if (ftFace == 0) throw new AWTError("font face:" + nativeName + " not loaded");

    /* Cache first 256 char widths for use by the getWidths method and for faster metric
    calculation as they are commonly used (ASCII) characters. */
    widths = new int[256];
    for (int i = 0; i < 256; i++) widths[i] = charWidthN(ftFace, (char) i);
  }
Пример #15
0
 public void changeFont() {
   font = DisplayOptions.getFont(fontName, fontStyle, fontSize);
   setFont(font);
   fontH = font.getSize();
   rHeight = fontH;
   if (!inEditMode) {
     if ((curDim.height > 0) && (rHeight > curDim.height)) {
       adjustFont(curDim.width, curDim.height);
     }
   }
   repaint();
 }
  protected SFont toZssFont(Font poiFont) {
    if (poiFont == null) return null; // ZSS-1138

    SFont font = null;
    final short fontIndex = poiFont.getIndex();
    if (importedFont.containsKey(fontIndex)) {
      font = importedFont.get(fontIndex);
    } else {
      font = createZssFont(poiFont);
      importedFont.put(fontIndex, font); // ZSS-677
    }
    return font;
  }
  protected SFont createZssFont(Font poiFont) {
    SFont font = book.createFont(true);
    // font
    font.setName(poiFont.getFontName());
    font.setBoldweight(PoiEnumConversion.toBoldweight(poiFont.getBoldweight()));
    font.setItalic(poiFont.getItalic());
    font.setStrikeout(poiFont.getStrikeout());
    font.setUnderline(PoiEnumConversion.toUnderline(poiFont.getUnderline()));

    font.setHeightPoints(poiFont.getFontHeightInPoints());
    font.setTypeOffset(PoiEnumConversion.toTypeOffset(poiFont.getTypeOffset()));
    font.setColor(book.createColor(BookHelper.getFontHTMLColor(workbook, poiFont)));

    return font;
  }
Пример #18
0
 public void setEditMode(boolean s) {
   if (s) {
     addMouseListener(ml);
     setOpaque(s);
     if (font != null) {
       setFont(font);
       fontH = font.getSize();
       rHeight = fontH;
     }
     defDim = getPreferredSize();
     curLoc.x = defLoc.x;
     curLoc.y = defLoc.y;
     curDim.width = defDim.width;
     curDim.height = defDim.height;
     xRatio = 1.0;
     yRatio = 1.0;
   } else {
     removeMouseListener(ml);
     if ((bg != null) || (isActive < 1)) setOpaque(true);
     else setOpaque(false);
   }
   inEditMode = s;
 }
Пример #19
0
  /**
   * Execute applet events. Here is the state transition diagram
   *
   * <pre>{@literal
   *   Note: (XXX) is the action
   *         APPLET_XXX is the state
   *  (applet code loaded) --> APPLET_LOAD -- (applet init called)--> APPLET_INIT --
   *  (applet start called) --> APPLET_START -- (applet stop called) --> APPLET_STOP --
   *  (applet destroyed called) --> APPLET_DESTROY --> (applet gets disposed) -->
   *   APPLET_DISPOSE --> ...
   * }</pre>
   *
   * In the legacy lifecycle model. The applet gets loaded, inited and started. So it stays in the
   * APPLET_START state unless the applet goes away(refresh page or leave the page). So the applet
   * stop method called and the applet enters APPLET_STOP state. Then if the applet is revisited, it
   * will call applet start method and enter the APPLET_START state and stay there.
   *
   * <p>In the modern lifecycle model. When the applet first time visited, it is same as legacy
   * lifecycle model. However, when the applet page goes away. It calls applet stop method and
   * enters APPLET_STOP state and then applet destroyed method gets called and enters APPLET_DESTROY
   * state.
   *
   * <p>This code is also called by AppletViewer. In AppletViewer "Restart" menu, the applet is jump
   * from APPLET_STOP to APPLET_DESTROY and to APPLET_INIT .
   *
   * <p>Also, the applet can jump from APPLET_INIT state to APPLET_DESTROY (in Netscape/Mozilla
   * case). Same as APPLET_LOAD to APPLET_DISPOSE since all of this are triggered by browser.
   */
  @Override
  public void run() {

    Thread curThread = Thread.currentThread();
    if (curThread == loaderThread) {
      // if we are in the loader thread, cause
      // loading to occur.  We may exit this with
      // status being APPLET_DISPOSE, APPLET_ERROR,
      // or APPLET_LOAD
      runLoader();
      return;
    }

    boolean disposed = false;
    while (!disposed && !curThread.isInterrupted()) {
      AppletEvent evt;
      try {
        evt = getNextEvent();
      } catch (InterruptedException e) {
        showAppletStatus("bail");
        return;
      }

      // showAppletStatus("EVENT = " + evt.getID());
      try {
        switch (evt.getID()) {
          case APPLET_LOAD:
            if (!okToLoad()) {
              break;
            }
            // This complexity allows loading of applets to be
            // interruptable.  The actual thread loading runs
            // in a separate thread, so it can be interrupted
            // without harming the applet thread.
            // So that we don't have to worry about
            // concurrency issues, the main applet thread waits
            // until the loader thread terminates.
            // (one way or another).
            if (loaderThread == null) {
              setLoaderThread(new Thread(null, this, "AppletLoader", 0, false));
              loaderThread.start();
              // we get to go to sleep while this runs
              loaderThread.join();
              setLoaderThread(null);
            } else {
              // REMIND: issue an error -- this case should never
              // occur.
            }
            break;

          case APPLET_INIT:
            // AppletViewer "Restart" will jump from destroy method to
            // init, that is why we need to check status w/ APPLET_DESTROY
            if (status != APPLET_LOAD && status != APPLET_DESTROY) {
              showAppletStatus("notloaded");
              break;
            }
            applet.resize(defaultAppletSize);

            if (PerformanceLogger.loggingEnabled()) {
              PerformanceLogger.setTime("Applet Init");
              PerformanceLogger.outputLog();
            }
            applet.init();

            // Need the default(fallback) font to be created in this AppContext
            Font f = getFont();
            if (f == null
                || "dialog".equals(f.getFamily().toLowerCase(Locale.ENGLISH))
                    && f.getSize() == 12
                    && f.getStyle() == Font.PLAIN) {
              setFont(new Font(Font.DIALOG, Font.PLAIN, 12));
            }

            // Validate the applet in event dispatch thread
            // to avoid deadlock.
            try {
              final AppletPanel p = this;
              Runnable r =
                  new Runnable() {
                    @Override
                    public void run() {
                      p.validate();
                    }
                  };
              AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
            } catch (InterruptedException ie) {
            } catch (InvocationTargetException ite) {
            }

            status = APPLET_INIT;
            showAppletStatus("inited");
            break;

          case APPLET_START:
            {
              if (status != APPLET_INIT && status != APPLET_STOP) {
                showAppletStatus("notinited");
                break;
              }
              applet.resize(currentAppletSize);
              applet.start();

              // Validate and show the applet in event dispatch thread
              // to avoid deadlock.
              try {
                final AppletPanel p = this;
                final Applet a = applet;
                Runnable r =
                    new Runnable() {
                      @Override
                      public void run() {
                        p.validate();
                        a.setVisible(true);

                        // Fix for BugTraq ID 4041703.
                        // Set the default focus for an applet.
                        if (hasInitialFocus()) {
                          setDefaultFocus();
                        }
                      }
                    };
                AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
              } catch (InterruptedException ie) {
              } catch (InvocationTargetException ite) {
              }

              status = APPLET_START;
              showAppletStatus("started");
              break;
            }

          case APPLET_STOP:
            if (status != APPLET_START) {
              showAppletStatus("notstarted");
              break;
            }
            status = APPLET_STOP;

            // Hide the applet in event dispatch thread
            // to avoid deadlock.
            try {
              final Applet a = applet;
              Runnable r =
                  new Runnable() {
                    @Override
                    public void run() {
                      a.setVisible(false);
                    }
                  };
              AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
            } catch (InterruptedException ie) {
            } catch (InvocationTargetException ite) {
            }

            // During Applet.stop(), any AccessControlException on an involved Class remains in
            // the "memory" of the AppletClassLoader.  If the same instance of the ClassLoader is
            // reused, the same exception will occur during class loading.  Set the
            // AppletClassLoader's
            // exceptionStatusSet flag to allow recognition of what had happened
            // when reusing AppletClassLoader object.
            try {
              applet.stop();
            } catch (java.security.AccessControlException e) {
              setExceptionStatus(e);
              // rethrow exception to be handled as it normally would be.
              throw e;
            }
            showAppletStatus("stopped");
            break;

          case APPLET_DESTROY:
            if (status != APPLET_STOP && status != APPLET_INIT) {
              showAppletStatus("notstopped");
              break;
            }
            status = APPLET_DESTROY;

            // During Applet.destroy(), any AccessControlException on an involved Class remains in
            // the "memory" of the AppletClassLoader.  If the same instance of the ClassLoader is
            // reused, the same exception will occur during class loading.  Set the
            // AppletClassLoader's
            // exceptionStatusSet flag to allow recognition of what had happened
            // when reusing AppletClassLoader object.
            try {
              applet.destroy();
            } catch (java.security.AccessControlException e) {
              setExceptionStatus(e);
              // rethrow exception to be handled as it normally would be.
              throw e;
            }
            showAppletStatus("destroyed");
            break;

          case APPLET_DISPOSE:
            if (status != APPLET_DESTROY && status != APPLET_LOAD) {
              showAppletStatus("notdestroyed");
              break;
            }
            status = APPLET_DISPOSE;

            try {
              final Applet a = applet;
              Runnable r =
                  new Runnable() {
                    @Override
                    public void run() {
                      remove(a);
                    }
                  };
              AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
            } catch (InterruptedException ie) {
            } catch (InvocationTargetException ite) {
            }
            applet = null;
            showAppletStatus("disposed");
            disposed = true;
            break;

          case APPLET_QUIT:
            return;
        }
      } catch (Exception e) {
        status = APPLET_ERROR;
        if (e.getMessage() != null) {
          showAppletStatus("exception2", e.getClass().getName(), e.getMessage());
        } else {
          showAppletStatus("exception", e.getClass().getName());
        }
        showAppletException(e);
      } catch (ThreadDeath e) {
        showAppletStatus("death");
        return;
      } catch (Error e) {
        status = APPLET_ERROR;
        if (e.getMessage() != null) {
          showAppletStatus("error2", e.getClass().getName(), e.getMessage());
        } else {
          showAppletStatus("error", e.getClass().getName());
        }
        showAppletException(e);
      }
      clearLoadAbortRequest();
    }
  }
Пример #20
0
  static void paintShadowTitle(
      Graphics g,
      String title,
      int x,
      int y,
      Color frente,
      Color shadow,
      int desp,
      int tipo,
      int orientation) {

    // Si hay que rotar la fuente, se rota
    Font f = g.getFont();
    if (orientation == SwingConstants.VERTICAL) {
      AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI / 2);
      f = f.deriveFont(rotate);
    }

    // Si hay que pintar sombra, se hacen un monton de cosas
    if (shadow != null) {
      int matrix = (tipo == THIN ? MATRIX_THIN : MATRIX_FAT);

      Rectangle2D rect = g.getFontMetrics().getStringBounds(title, g);

      int w, h;
      if (orientation == SwingConstants.HORIZONTAL) {
        w = (int) rect.getWidth() + 6 * matrix; // Hay que dejar espacio para las sombras y el borde
        h = (int) rect.getHeight() + 6 * matrix; // que ConvolveOp ignora por el EDGE_NO_OP
      } else {
        h = (int) rect.getWidth() + 6 * matrix; // Hay que dejar espacio para las sombras y el borde
        w = (int) rect.getHeight() + 6 * matrix; // que ConvolveOp ignora por el EDGE_NO_OP
      }

      // La sombra del titulo
      BufferedImage iTitulo = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
      BufferedImage iSombra = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

      Graphics2D g2 = iTitulo.createGraphics();
      g2.setRenderingHint(
          RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

      g2.setFont(f);
      g2.setColor(shadow);
      g2.drawString(title, 3 * matrix, 3 * matrix); // La pintamos en el centro

      ConvolveOp cop =
          new ConvolveOp((tipo == THIN ? kernelThin : kernelFat), ConvolveOp.EDGE_NO_OP, null);
      cop.filter(iTitulo, iSombra); // A ditorsionar

      // Por fin, pintamos el jodio titulo
      g.drawImage(
          iSombra,
          x - 3 * matrix + desp, // Lo llevamos a la posicion original y le sumamos 1
          y - 3 * matrix + desp, // para que la sombra quede pelin desplazada
          null);
    }

    // Si hay que pintar el frente, se pinta
    if (frente != null) {
      g.setFont(f);
      g.setColor(frente);
      g.drawString(title, x, y);
    }
  }
Пример #21
0
  public EditorPaneHTMLHelp(String htmlFile) {
    if (GlobalValues.useSystemBrowserForHelp) {
      Desktop d = GlobalValues.desktop;
      try {
        // create a temp file
        GlobalValues.forHTMLHelptempFile = new File("tempHTMLHelpSynthetic.html");
        FileWriter fw = new FileWriter(GlobalValues.forHTMLHelptempFile);

        java.util.List<String> list = readTextFromJar(htmlFile);
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
          fw.write(it.next() + "\n");
        }

        String canonicalPathOfFile = GlobalValues.forHTMLHelptempFile.getCanonicalPath();
        URL urlFile = new URL("file://" + canonicalPathOfFile);
        URI uriOfFile = urlFile.toURI();

        fw.close();

        d.browse(uriOfFile);

      } catch (Exception e) {
        e.printStackTrace();
      }

    } else {
      URL initialURL = getClass().getResource(htmlFile);

      font = GlobalValues.htmlfont;

      String title = "HTML Help";
      setTitle(title);

      final Stack<String> urlStack = new Stack<String>();
      final JEditorPane editorPane;

      editorPane = new JEditorPane(new HTMLEditorKit().getContentType(), " ");

      editorPane.setOpaque(false);
      editorPane.setBorder(null);
      editorPane.setEditable(false);

      JPanel magPanel = new JPanel();

      magnificationFactor = GlobalValues.helpMagnificationFactor;
      magFactor = new JTextField(Double.toString(magnificationFactor));

      JButton magButton = new JButton("Set Magnification: ");
      magButton.addActionListener(
          new ActionListener() {

            public void actionPerformed(ActionEvent e) {
              magnificationFactor = Double.parseDouble(magFactor.getText());
              GlobalValues.helpMagnificationFactor = magnificationFactor;
            }
          });

      magPanel.setLayout(new GridLayout(1, 2));
      magPanel.add(magButton);
      magPanel.add(magFactor);

      final JTextField url = new JTextField(initialURL.toString());

      // set up hyperlink listener
      editorPane.setEditable(false);

      try {
        // remember URL for back button
        urlStack.push(initialURL.toString());
        // show URL in text field
        url.setText(initialURL.toString());

        // add a CSS rule to force body tags to use the default label font
        // instead of the value in javax.swing.text.html.default.csss

        String bodyRule =
            "body { font-family: "
                + font.getFamily()
                + "; "
                + "font-size: "
                + font.getSize() * GlobalValues.helpMagnificationFactor
                + "pt; }";
        ((HTMLDocument) editorPane.getDocument()).getStyleSheet().addRule(bodyRule);

        editorPane.setPage(initialURL);

        editorPane.firePropertyChange("dummyProp", true, false);

      } catch (IOException e) {
        editorPane.setText("Exception: " + e);
      }

      editorPane.addPropertyChangeListener(
          new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent evt) {

              String bodyRule =
                  "body { font-family: "
                      + font.getFamily()
                      + "; "
                      + "font-size: "
                      + font.getSize() * GlobalValues.helpMagnificationFactor
                      + "pt; }";
              ((HTMLDocument) editorPane.getDocument()).getStyleSheet().addRule(bodyRule);
            }
          });

      editorPane.addHyperlinkListener(
          new HyperlinkListener() {
            public void hyperlinkUpdate(HyperlinkEvent event) {
              if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                try {
                  // remember URL for back button
                  urlStack.push(event.getURL().toString());
                  // show URL in text field
                  url.setText(event.getURL().toString());
                  editorPane.setPage(event.getURL());

                  editorPane.firePropertyChange("dummyProp", true, false);

                } catch (IOException e) {
                  editorPane.setText("Exception: " + e);
                }
              }
            }
          });

      // set up checkbox for toggling edit mode
      final JCheckBox editable = new JCheckBox();
      editable.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              editorPane.setEditable(editable.isSelected());
            }
          });

      // set up load button for loading URL
      ActionListener listener =
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              try {
                // remember URL for back button
                urlStack.push(url.getText());
                editorPane.setPage(url.getText());

                editorPane.firePropertyChange("dummyProp", true, false);

              } catch (IOException e) {
                editorPane.setText("Exception: " + e);
              }
            }
          };

      JButton loadButton = new JButton("Load/Magnify");
      loadButton.addActionListener(listener);
      url.addActionListener(listener);

      // set up back button and button action

      JButton backButton = new JButton("Back");
      backButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              if (urlStack.size() <= 1) return;
              try {
                // get URL from back button
                urlStack.pop();
                // show URL in text field
                String urlString = urlStack.peek();
                url.setText(urlString);
                editorPane.setPage(urlString);

                editorPane.firePropertyChange("dummyProp", true, false);

              } catch (IOException e) {
                editorPane.setText("Exception: " + e);
              }
            }
          });

      JPanel allPanel = new JPanel(new BorderLayout());

      // put all control components in a panel

      JPanel ctrlPanel = new JPanel(new BorderLayout());
      JPanel urlPanel = new JPanel();
      urlPanel.add(new JLabel("URL"));
      urlPanel.add(url);
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(loadButton);
      buttonPanel.add(backButton);
      buttonPanel.add(new JLabel("Editable"));
      buttonPanel.add(magPanel);
      buttonPanel.add(editable);
      ctrlPanel.add(buttonPanel, BorderLayout.NORTH);
      ctrlPanel.add(urlPanel, BorderLayout.CENTER);

      allPanel.add(ctrlPanel, BorderLayout.NORTH);
      allPanel.add(new JScrollPane(editorPane), BorderLayout.CENTER);

      add(allPanel);
    }
  }
Пример #22
0
  void updateCaretPosition() {
    int x = getCursorX();
    int y = getCursorY();

    caretLeft = inputFont.substringWidth(vectorLines.elementAt(y).toString(), 0, x);
  }
Пример #23
0
 /** Default constructor Makes an INFont with size of 12 Plain style and with the Arial Font */
 public INFont() {
   this.size = 12;
   this.style = FontStyle.PLAIN;
   this.loadedFont = Font.decode("Arial-12");
 }
Пример #24
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);
  }
Пример #25
0
  public GamePanel(String name, int l) {
    setFocusable(true);
    grabFocus();
    addMouseListener(this);
    addMouseMotionListener(this);
    addKeyListener(this);
    keys = new boolean[10000];

    try {
      scoreFont =
          Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(new File("BRLNSB.ttf")))
              .deriveFont(0, 32);
    } catch (IOException ioe) {
      System.out.println("error loading BRLNSB.tff");
    } catch (FontFormatException ffe) {
      System.out.println("Something went wrong with the font.");
    }

    gameBckgrnd = new ImageIcon("Backgroundimage.png").getImage();
    for (int i = 1; i < 7; i++) {
      magnetList.add(new ImageIcon("gamelayerstuff/powerups/magnet" + i + ".png").getImage());
    }

    coinPic = new ImageIcon("gamelayerstuff/coins/byellowcoin1.png").getImage();
    player1 = new Player(200, 300, 100, "sheldon");

    click = false;
    ground = true;
    pause = false;
    lvlClear = false;
    die = false;
    musicOn = true;

    player1.setVelo(150);
    player1.setInvi(true);
    // ------------------------------------------------------------------------------------------------------------------------------------
    // Sound
    coinSound = Applet.newAudioClip(getClass().getResource("coin_pickup_2.wav"));
    clicked = Applet.newAudioClip(getClass().getResource("menu_deselect.wav"));
    starSound = Applet.newAudioClip(getClass().getResource("star.wav"));
    bounce = Applet.newAudioClip(getClass().getResource("grav_step_4.wav"));
    bckGrndMusic = Applet.newAudioClip(getClass().getResource("bgmusic00.wav"));
    bckGrndMusic.loop();
    // ------------------------------------------------------------------------------------------------------------------------------------

    // distance=0;
    score = 0;
    coins = 0;
    level = 1;
    prevLvl = level;
    backy = 0;
    height = backy;
    dieHeight = 0;
    dieMenuHeight = 0;

    pauseB = new SButton(400, 670, "pause", "");
    resumeB = new SButton(100, 500, "resume", "");
    menuB = new SButton(100, 620, "back", "");
    muteB = new SButton(400, 600, "mute", "");
    unmuteB = new SButton(400, 600, "unmute", "");
    // System.out.println("characters/"+name+"/"+name+"35.png");
  }
  private void drawPlot(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(
        RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, getWidth(), getHeight());

    double activeWidth = getWidth() - leftMargin - rightMargin;
    double activeHeight = getHeight() - topMargin - bottomMargin;
    int bottomY = getHeight() - bottomMargin;
    int rightX = getWidth() - rightMargin;

    // draw data line
    int x1, x2, y1, y2;
    g2d.setColor(Color.red);
    for (int i = 1; i < numComponents; i++) {
      x1 = (int) (leftMargin + ((double) (i - 1) / (numComponents - 1)) * activeWidth);
      y1 = (int) (bottomY - (plotData[i - 1][plotIndex] * 10.0) / 1000 * activeHeight);
      x2 = (int) (leftMargin + ((double) (i) / (numComponents - 1)) * activeWidth);
      y2 = (int) (bottomY - (plotData[i][plotIndex] * 10) / 1000 * activeHeight);
      g2d.drawLine(x1, y1, x2, y2);
    }

    // draw data points
    int radius = 2;
    for (int i = 0; i < numComponents; i++) {
      x1 = (int) (leftMargin + ((double) (i) / (numComponents - 1)) * activeWidth);
      y1 = (int) (bottomY - (plotData[i][plotIndex] * 10.0) / 1000 * activeHeight);
      g2d.drawOval(x1 - radius - 1, y1 - radius - 1, 2 * radius + 2, 2 * radius + 2);
    }

    // draw axes
    g2d.setColor(Color.black);
    g2d.drawLine(leftMargin, bottomY, rightX, bottomY);
    g2d.drawLine(leftMargin, bottomY, leftMargin, topMargin);
    g2d.drawLine(leftMargin, topMargin, rightX, topMargin);
    g2d.drawLine(rightX, bottomY, rightX, topMargin);

    // draw ticks
    int tickSize = 4;
    for (int i = 1; i <= numComponents; i++) {
      x1 = (int) (leftMargin + ((double) (i - 1) / (numComponents - 1)) * activeWidth);
      g2d.drawLine(x1, bottomY, x1, bottomY + tickSize);
    }

    for (int i = 0; i <= 1000; i += 100) {
      y1 = (int) (bottomY - i / 1000.0 * activeHeight);
      g2d.drawLine(leftMargin, y1, leftMargin - tickSize, y1);
    }

    // labels
    DecimalFormat df = new DecimalFormat("#,###,###.###");
    Font font = new Font("SanSerif", Font.PLAIN, 11);
    FontMetrics metrics = g.getFontMetrics(font);
    int hgt, adv;
    hgt = metrics.getHeight();

    // x-axis labels
    String label;
    for (int i = 1; i <= numComponents; i++) {
      label = String.valueOf(i);
      x1 = (int) (leftMargin + ((double) (i - 1) / (numComponents - 1)) * activeWidth);
      adv = metrics.stringWidth(label) / 2;
      g2d.drawString(label, x1 - adv, bottomY + hgt + 4);
    }
    label = "Component";
    adv = metrics.stringWidth(label);
    int xAxisMidPoint = (int) (leftMargin + activeWidth / 2);
    g2d.drawString(label, xAxisMidPoint - adv / 2, bottomY + 2 * hgt + 6);

    // y-axis labels

    // rotate the font
    Font oldFont = g.getFont();
    Font f = oldFont.deriveFont(AffineTransform.getRotateInstance(-Math.PI / 2.0));
    g2d.setFont(f);

    int yAxisMidPoint = (int) (topMargin + activeHeight / 2);
    int offset;
    label = "Explained Variance (%)";
    offset = metrics.stringWidth("100.0") + 12 + hgt;
    adv = metrics.stringWidth(label);
    g2d.drawString(label, leftMargin - offset, yAxisMidPoint + adv / 2);

    // replace the rotated font.
    g2d.setFont(oldFont);

    df = new DecimalFormat("0.0");
    for (int i = 0; i <= 1000; i += 100) {
      label = df.format(i / 10);
      y1 = (int) (bottomY - i / 1000.0 * activeHeight);
      adv = metrics.stringWidth(label);
      g2d.drawString(label, leftMargin - adv - 12, y1 + hgt / 2);
    }

    // title

    // bold font
    oldFont = g.getFont();
    font = font = new Font("SanSerif", Font.BOLD, 12);
    g2d.setFont(font);

    label = "PCA Scree Plot";
    adv = metrics.stringWidth(label);
    g2d.drawString(label, getWidth() / 2 - adv / 2, topMargin - hgt - 5);

    g2d.setFont(oldFont);
  }
Пример #27
0
  public static void convertCangjieHK() {
    try {
      Font font = new Font("Droid Sans Fallback", 16, Font.PLAIN);
      ArrayList<String> codeList = new ArrayList<String>();
      HashMap<String, ArrayList<CangjieChar>> codeMap =
          new HashMap<String, ArrayList<CangjieChar>>();
      int totalCangjieColumn = 7;
      FileInputStream fis = new FileInputStream("cangjie3.txt");
      InputStreamReader input = new InputStreamReader(fis, "UTF-8");
      BufferedReader reader = new BufferedReader(input);
      String str = null;
      int index = 0;
      int total = 0;
      char column[] = new char[5];
      boolean hkchar = false;

      System.out.println("#define CANGJIE_COLUMN " + totalCangjieColumn);
      System.out.println("const jchar cangjie[][CANGJIE_COLUMN] = {");
      do {
        str = reader.readLine();
        if (str == null) break;
        if (str.compareTo("#####") == 0) {
          hkchar = true;
          continue;
        }
        index = str.indexOf('\t');
        if (index < 0) index = str.indexOf(' ');
        if (index > 0 && font.canDisplay(str.charAt(index + 1))) {
          int type = Character.getType(str.charAt(index + 1));
          if (Character.isLetter(str.charAt(index + 1))
              || type == Character.START_PUNCTUATION
              || type == Character.END_PUNCTUATION
              || type == Character.OTHER_PUNCTUATION
              || type == Character.MATH_SYMBOL
              || type == Character.DASH_PUNCTUATION
              || type == Character.CONNECTOR_PUNCTUATION
              || type == Character.OTHER_SYMBOL
              || type == Character.INITIAL_QUOTE_PUNCTUATION
              || type == Character.FINAL_QUOTE_PUNCTUATION
              || type == Character.SPACE_SEPARATOR) {
            // System.out.print("\t { ");
            // for (int count = 0; count < 5; count++) {
            //     if (count < index) {
            // 	column[count] = str.charAt(count);
            // 	if (column[count] < 'a' || column[count] > 'z') column[count] = 0;
            // 	if (((int) column[count]) >= 10 || ((int) column[count]) <= 99) System.out.print('
            // ');
            // 	if (((int) column[count]) <= 9) System.out.print(' ');
            // 	System.out.print(((int)	column[count]));
            //     } else {
            // 	System.out.print("  0");
            //     }
            //     System.out.print(", ");
            // }
            // System.out.println((int) str.charAt(index + 1) + " }, ");

            String cangjie = str.substring(0, index).trim();
            char ch = str.charAt(index + 1);
            if (!codeList.contains(cangjie)) codeList.add(cangjie);
            ArrayList<CangjieChar> list = null;
            if (codeMap.containsKey(cangjie)) {
              list = codeMap.get(cangjie);
            } else {
              list = new ArrayList<CangjieChar>();
            }
            CangjieChar cc = new CangjieChar(ch, hkchar);
            list.add(cc);
            codeMap.put(cangjie, list);

            total++;
          } else {
            System.err.println(
                "Character Not Found : "
                    + str.charAt(index + 1)
                    + " "
                    + Character.getType(str.charAt(index + 1)));
          }
        }
      } while (str != null);

      Collections.sort(codeList);

      for (int count0 = 0; count0 < codeList.size(); count0++) {
        String _str = codeList.get(count0);
        ArrayList<CangjieChar> ca = codeMap.get(_str);
        for (int count1 = 0; count1 < ca.size(); count1++) {
          for (int count2 = 0; count2 < 5; count2++) {
            if (count2 < _str.length()) System.out.print("'" + _str.charAt(count2) + "', ");
            else System.out.print("  0, ");
          }
          System.out.println(((int) ca.get(count1).c) + ", " + (ca.get(count1).hk ? 1 : 0) + ", ");
        }
      }

      System.out.println("};");
      System.out.println("jint cangjie_index[" + total + "];");
      System.out.println("jint cangjie_frequency[" + total + "];");
      reader.close();
      input.close();
      fis.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #28
0
  public void fillPopupMenu() {
    JMenuItem item;
    TextImageIcon textIcon;
    StatementHistory history;
    int rowCount = 0;
    int numRows = 0;
    Insets margin = new Insets(0, 0, 0, 0);

    // Get the font defined in the displayOptions panel for menus
    Font ft = DisplayOptions.getFont("Menu1");
    // We need a fairly small font, so make it 2 smaller.
    int size = ft.getSize();
    // If larger than 12, subtract 2
    if (size > 12) size -= 2;
    Font font = DisplayOptions.getFont(ft.getName(), ft.getStyle(), size);

    // This flag is used so that we only fill the menu when needed
    if (menuAlreadyFilled) return;

    menuAlreadyFilled = true;

    history = sshare.statementHistory();

    ArrayList list = history.getNamedStatementList();
    Color bgColor = Util.getBgColor();
    // Only show the Saved Statements section if there are some.
    if (list != null && list.size() != 0) {
      item = popup.add("Saved Statements");
      rowCount++;
      //	    item.setForeground(Color.blue);
      //	    item.setBackground(bgColor);
      item.setFont(font);
      item.setMargin(margin);
      popup.add(item);

      for (int i = 0; i < list.size(); i++) {
        ArrayList nameNlabel = (ArrayList) list.get(i);
        // first item in nameNlabel is name and second is label
        item = popup.add("  " + (String) nameNlabel.get(1));
        rowCount++;
        item.setActionCommand("save:" + (String) nameNlabel.get(0));
        //		item.setBackground(bgColor);
        item.addActionListener(popActionListener);
        item.setFont(font);
        item.setMargin(margin);
      }
    }
    // the rest of menu (return object types, statement types, etc.)
    ShufflerService shufflerService = sshare.shufflerService();
    ArrayList objTypes = shufflerService.getAllMenuObjectTypes();

    for (int i = 0; i < objTypes.size(); i++) {
      String objType = (String) objTypes.get(i);

      // Do not display menu for DB_AVAIL_SUB_TYPES
      if (objType.equals(Shuf.DB_AVAIL_SUB_TYPES)) continue;

      // addSeparator looks bad using GridLayout because it creates rows
      // and columns which are all equal in size.  It cannot have a row
      // with a separator which is a different height than the other
      // rectangles it creates. So just use dashes.
      item = popup.add(separator);
      item.setFont(font);
      item.setMargin(margin);
      rowCount++;
      item = popup.add(shufflerService.getCategoryLabel(objType));
      rowCount++;
      //	    item.setForeground(Color.blue);
      item.setActionCommand("title:" + objType);
      //	    item.setBackground(bgColor);
      item.addActionListener(popActionListener);
      item.setFont(font);
      item.setMargin(margin);

      ArrayList menuStrings = shufflerService.getmenuStringsThisObj(objType);

      // If current rowCount plus the next section size is too big,
      // specify the numRows to the current value of rowCount -1.
      // That is, put this next section in a new column.
      // 47 is emperical number of rows to fit 90% full screen.
      if (numRows == 0 && rowCount - 1 + menuStrings.size() > 44) {

        numRows = rowCount - 2;
      }

      for (int j = 0; j < menuStrings.size(); j++) {
        String menuString = (String) menuStrings.get(j);
        item = popup.add("  " + menuString);
        rowCount++;
        item.setActionCommand("command:" + objType + "/" + menuString);
        //		item.setBackground(bgColor);
        item.addActionListener(popActionListener);
        item.setFont(font);
        item.setMargin(margin);
      }
      // The spotter menu changes dynamically when
      // the list of saved statements changes.
      history.addStatementListener(
          new StatementAdapter() {
            public void saveListChanged() {
              refreshSaveMenu();
            }
          });
    }

    if (numRows == 0) numRows = rowCount;

    GridLayoutCol lm = new GridLayoutCol(numRows, 0);
    popup.setLayout(lm);
  }
Пример #29
0
  public static void convertQuick() {
    try {

      HashMap<String, ArrayList<Character>> charList = new HashMap<String, ArrayList<Character>>();

      Font font = new Font("Droid Sans Fallback", 16, Font.PLAIN);
      int totalQuickColumn = 3;
      FileInputStream fis = new FileInputStream("quick-classic.txt");
      InputStreamReader input = new InputStreamReader(fis, "UTF-8");
      BufferedReader reader = new BufferedReader(input);
      String str = null;
      int index = 0;
      int total = 0;
      ArrayList<String> keyList = new ArrayList<String>();
      System.out.println("#define QUICK_COLUMN " + totalQuickColumn);
      System.out.println("const jchar quick[][QUICK_COLUMN] = {");
      do {
        str = reader.readLine();
        if (str == null) break;
        index = str.indexOf('\t');
        if (index < 0) index = str.indexOf(' ');
        if (index > 0) {
          if (font.canDisplay(str.charAt(index + 1))) {
            StringBuffer sb = new StringBuffer();
            // System.out.print("\t { ");
            if ((int) str.charAt(1) == 9 || str.charAt(1) == ' ') {
              // System.out.print("'" + str.charAt(0) + "',   0, ");
              sb.append(str.charAt(0));
            } else {
              sb.append(str.charAt(0));
              sb.append(str.charAt(1));
              // System.out.print("'" + str.charAt(0) + "', '" + str.charAt(1) + "', ");
            }
            String key = sb.toString();
            // System.out.println((int) str.charAt(index + 1) + " }, ");
            Character ch = new Character(str.charAt(index + 1));

            if (!keyList.contains(key)) keyList.add(key);

            if (charList.containsKey(key)) {
              charList.get(key).add(ch);
            } else {
              ArrayList<Character> c = new ArrayList<Character>();
              c.add(ch);
              charList.put(key, c);
            }
            total++;
          }
        }
      } while (str != null);
      for (int count = 0; count < keyList.size(); count++) {
        String k = keyList.get(count);
        ArrayList<Character> l = charList.get(k);
        for (int loop = 0; loop < l.size(); loop++) {
          if (k.length() == 1) {
            System.out.println("\t { '" + k.charAt(0) + "',   0, " + l.get(loop) + " }, ");
          } else {
            System.out.println(
                "\t { '" + k.charAt(0) + "', '" + k.charAt(1) + "', " + l.get(loop) + " }, ");
          }
        }
      }
      System.out.println("};");
      System.out.println("jint quick_index[" + total + "];");
      System.out.println("jint quick_frequency[" + total + "];");
      reader.close();
      input.close();
      fis.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #30
0
  public MancalaPanel(LetsPlayMancala game) {

    // ------------------------------------------------------------------------------
    // Import font "Belta Regular"
    // -----------------------------------------------------------------------------
    try {
      InputStream in = MancalaPanel.class.getResourceAsStream("belta-regular.ttf");
      Font font = Font.createFont(Font.TRUETYPE_FONT, in);
    } catch (Exception ex) {
      System.out.println("Font couldn't be loaded.");
    }

    // ----------------------------------------------------------------------------
    // Set background image
    // ----------------------------------------------------------------------------
    imageFile = "/Images/GameBackground.png";
    this.game = game;
    SMALL_PIT_COUNT = 12;

    setLayout(new BorderLayout());

    add(northWindowPanel(), BorderLayout.NORTH);
    add(westWindowPanel(), BorderLayout.WEST);
    add(makeBoardPanel(), BorderLayout.CENTER);
    add(eastWindowPanel(), BorderLayout.EAST);
    add(southWindowPanel(), BorderLayout.SOUTH);

    winners = new LinkedStack<String>();
    winnersLabel = new JLabel();

    resultFrame = new JFrame();
    boardResultPanel = new BkImagePanel("/Images/board2.png");
    resultNorth = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 50));
    resultNorth.setOpaque(false);
    resultCenter = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
    resultCenter.setOpaque(false);
    resultSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
    resultSouth.setOpaque(false);

    playAgainBtn.setPreferredSize(new Dimension(240, 80));
    playAgainBtn.setBackground(new Color(135, 17, 76));
    playAgainBtn.setForeground(Color.white);
    playAgainBtn.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    playAgainBtn.setFont(new Font("Belta Regular", Font.BOLD, 40));
    playAgainBtn.addActionListener(new ButtonListener());

    scoresBtn.setPreferredSize(new Dimension(340, 80));
    scoresBtn.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    scoresBtn.addActionListener(new ButtonListener());

    quitBtn.setPreferredSize(new Dimension(150, 80));
    quitBtn.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    quitBtn.addActionListener(new ButtonListener());

    result = new JLabel();
    result.setFont(new Font("Belta Regular", Font.BOLD, 40));
    result.setForeground(Color.white);
    result.setBackground(new Color(0, 158, 121));
    result.setBorder(BorderFactory.createLineBorder(Color.white, 6));
    result.setOpaque(true);
    result.setPreferredSize(new Dimension(380, 80));

    winnersLabel = new JLabel();
    winnersLabel.setFont(new Font("Belta Regular", Font.BOLD, 40));
    winnersLabel.setForeground(Color.white);
    winnersLabel.setPreferredSize(new Dimension(420, 200));

    boardResultPanel.setLayout(new BorderLayout(50, 50));
    boardResultPanel.setPreferredSize(new Dimension(800, 700));
    boardResultPanel.setBackground(Color.yellow);
    boardResultPanel.add(resultNorth, BorderLayout.NORTH);
    boardResultPanel.add(resultCenter, BorderLayout.CENTER);
    boardResultPanel.add(resultSouth, BorderLayout.SOUTH);

    resultCenter.add(winnersLabel);
    resultSouth.add(scoresBtn);
    resultSouth.add(playAgainBtn);
    resultSouth.add(quitBtn);

    resultFrame.add(boardResultPanel);
  }