/**
   * actionPerformed() handles clicks on the button. It takes the data from the input JTextFields,
   * and sends them to the GradeCalculater class to calculate a running average and computes the
   * letter grade, which are displayed in TextFields.
   *
   * @param e -- the ActionEvent the generated this system call
   */
  public void actionPerformed(ActionEvent e) {

    double count, grade = 0, ave;
    DecimalFormat df = new DecimalFormat("0.00");

    String inputString = inputField.getText();

    // HINT: use try/catch blocks to catch bad input to parseDouble()
    // Type mismatch
    // check for range too
    boolean error = true;

    try {
      grade = Double.parseDouble(inputString);
      error = false;
    } catch (Exception e1) {
      System.out.println("input a number");
    }

    // HINT: reject a bad grade in some way (the modified addGrade will return false
    // there is a problem with the grade

    // HINT: output grade count along with average and letter grade
    if (error == false) {
      inputField.setText("");
      calculator.addGrade(grade);
      ave = calculator.calcAvg();
      count = calculator.getCount();
      String average = "" + df.format(ave);
      String letterGrade = calculator.calcLetterGrade();
      resultField.setText(average + " " + letterGrade + " " + count);
    }
  } // actionPeformed()
Exemplo n.º 2
0
 public static String memoryToString() {
   DecimalFormat fmt = new DecimalFormat("0.0");
   return "Memory: "
       + fmt.format(RUNTIME.maxMemory() / 1048576D)
       + "MByte maximum, "
       + fmt.format(RUNTIME.totalMemory() / 1048576D)
       + "MByte total, "
       + fmt.format(RUNTIME.totalMemory() / 1048576D)
       + "MByte free";
 }
Exemplo n.º 3
0
  // calculate and display amounts
  private void calculateJButtonActionPerformed(ActionEvent event) {
    resultJTextArea.setText("Rate (%)\tAmount after 10 years");
    DecimalFormat dollars = new DecimalFormat("$0.00");

    int principal = Integer.parseInt(principalJTextField.getText());

    // for loop to calculate interest
    for (int rate = 5; rate <= 10; rate++) {
      double amount = (double) principal * Math.pow(1 + ((double) rate / 100), 10);
      resultJTextArea.append("\n" + rate + "\t" + dollars.format(amount));
    } // end for
  } // end method calculateJButtonActionPerformed
Exemplo n.º 4
0
 /* paint() - get current time and draw (centered) in Component. */
 public void paint(Graphics g) {
   Calendar myCal = Calendar.getInstance();
   StringBuffer sb = new StringBuffer();
   sb.append(tf.format(myCal.get(Calendar.HOUR)));
   sb.append(':');
   sb.append(tflz.format(myCal.get(Calendar.MINUTE)));
   sb.append(':');
   sb.append(tflz.format(myCal.get(Calendar.SECOND)));
   String s = sb.toString();
   FontMetrics fm = getFontMetrics(getFont());
   int x = (getSize().width - fm.stringWidth(s)) / 2;
   // System.out.println("Size is " + getSize());
   g.drawString(s, x, 10);
 }
  // calculate and display amounts
  private void calculateJButtonActionPerformed(ActionEvent event) {
    // declare variables to store user input
    double principal = Double.parseDouble(principalJTextField.getText());
    double rate = Double.parseDouble(interestRateJTextField.getText());

    Integer integerObject = (Integer) yearsJSpinner.getValue();
    Integer year = integerObject.intValue();

    yearlyBalanceJTextArea.setText("Year\tAmount on Deposit");
    DecimalFormat dollars = new DecimalFormat("$0.00");

    // calculate the total value for each year
    for (int count = 1; count <= year; count++) {
      double amount = principal * Math.pow((1 + rate / 100), count);
      yearlyBalanceJTextArea.append("\n" + count + "\t" + dollars.format(amount));
    } // end for
  } // end method calculateJButtonActionPerformed
Exemplo n.º 6
0
 /**
  * Adds an editable text field containing the hours spent on a project.
  *
  * @param gbl The layout to add the text field to.
  * @param gbc The layout constraints to use.
  * @param row The row to link against.
  * @param hours The number of hours spent on the project.
  * @see {@link #addRow(GridBagLayout, GridBagConstraints, String, double)}
  */
 private void addMiddleField(GridBagLayout gbl, GridBagConstraints gbc, Row row, double hours) {
   row.hoursTF.setText(decimalFormat.format(hours));
   gbc.gridx = 1;
   gbc.weightx = 1;
   gbl.setConstraints(row.hoursTF, gbc);
   gbc.weightx = 0;
   reviewPanel.add(row.hoursTF);
 }
Exemplo n.º 7
0
  //    int frame = 0;
  public void paint(Graphics g) {
    // System.out.println("frame: " + (frame++));
    lStatus.setText(
        "t = "
            + df.format(md.dt * md.step)
            + ", "
            + "N = "
            + md.N
            + ", "
            + "E/N = "
            + df.format(md.E / md.N)
            + ", "
            + "U/N = "
            + df.format(md.U / md.N)
            + ", "
            + "K/N = "
            + df.format(md.K / md.N)
            + ", "
            + "p = "
            + df.format(md.p)
            + ";");
    tAvK.setText(df.format(md.avK.getAve() / md.N) + "  ");
    tAvU.setText(df.format(md.avU.getAve() / md.N) + "  ");
    tTemp.setText(df.format((2 * md.K) / (3 * (md.N - 1))) + "  ");
    tAvp.setText(df.format(md.avp.getAve()) + "  ");
    canvas.refresh(md.getXWrap(), md.N, true, false);
    cpnl.repaint();
    spnl.repaint();

    try {

      PrintWriter wavefunc =
          new PrintWriter(new FileOutputStream(new File("energyData.txt"), true));
      wavefunc.print(md.E / md.N + " " + md.K / md.N + " " + md.U / md.N);
      wavefunc.println();
      wavefunc.close();
    } catch (IOException ex) {
    }

    try {

      PrintWriter tempwriter =
          new PrintWriter(new FileOutputStream(new File("tempData.txt"), true));
      tempwriter.print(df.format((2 * md.K) / (3 * (md.N - 1))));
      tempwriter.println();
      tempwriter.close();
    } catch (IOException ex) {
    }
  }
 public ScientificRenderer(int sigfigs) {
   sigfigs = Math.min(sigfigs, 6);
   if (format instanceof DecimalFormat) {
     String pattern = "0.0"; // $NON-NLS-1$
     for (int i = 0; i < sigfigs - 1; i++) {
       pattern += "0"; // $NON-NLS-1$
     }
     pattern += "E0"; // $NON-NLS-1$
     ((DecimalFormat) format).applyPattern(pattern);
   }
 }
Exemplo n.º 9
0
 /**
  * This function re-computes the total number of hours for the selected period. It is ran every
  * time the user edits a text field specifying the number of hours for a particular top-level
  * project. Percentage labels are also updated.
  */
 private void recomputeTotal() {
   double total = 0;
   for (Row row : rows.values()) {
     try {
       row.hours = Double.parseDouble(row.hoursTF.getText());
       total += row.hours;
       row.hoursTF.setForeground(normalColour);
     } catch (NumberFormatException e) {
       row.hoursTF.setForeground(errorColour);
       totalLabel.setText("ERROR");
       totalLabel.setForeground(errorColour);
       return;
     }
   }
   totalLabel.setText(decimalFormat.format(total));
   totalLabel.setForeground(normalColour);
   for (Row row : rows.values()) {
     String percentS = decimalFormat.format(total == 0 ? 0 : 100 * row.hours / total);
     row.percentL.setText("(" + percentS + "%)");
   }
   pack();
 }
Exemplo n.º 10
0
 private String generateOverviewText() throws InsufficientDataException {
   StringBuilder sb = new StringBuilder();
   final String team = config.getTeam();
   double total = checkTotal();
   final String nl = System.getProperty("line.separator");
   for (Entry<String, Row> entry : rows.entrySet()) {
     double hours = Double.parseDouble(entry.getValue().hoursTF.getText());
     double fraction = hours / total;
     if (fraction < 0.004) continue;
     String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey();
     sb.append(line + nl);
   }
   return sb.toString();
 }
Exemplo n.º 11
0
  static {
    points = Collections.synchronizedList(new ArrayList<DrawObject>());
    lines = Collections.synchronizedList(new ArrayList<DrawObject>());
    ovals = Collections.synchronizedList(new ArrayList<DrawObject>());
    rectangles = Collections.synchronizedList(new ArrayList<DrawObject>());
    images = Collections.synchronizedList(new ArrayList<DrawObject>());
    labels = Collections.synchronizedList(new ArrayList<DrawObject>());
    scribbles = Collections.synchronizedList(new ArrayList<DrawObject>());
    eqnLines = Collections.synchronizedList(new ArrayList<DrawObject>());

    animPoints = Collections.synchronizedList(new ArrayList<DrawObject>());
    animLines = Collections.synchronizedList(new ArrayList<DrawObject>());
    animOvals = Collections.synchronizedList(new ArrayList<DrawObject>());
    animRectangles = Collections.synchronizedList(new ArrayList<DrawObject>());
    animLabels = Collections.synchronizedList(new ArrayList<DrawObject>());

    df.setMaximumFractionDigits(4);
  }
Exemplo n.º 12
0
 void print(String name, double value) {
   g.drawString(name + ":" + df.format(value), x, y += 20);
 }
Exemplo n.º 13
0
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;
    RenderingHints rh = g2d.getRenderingHints();
    rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHints(rh);

    // Background.
    D = this.getSize();
    g.setColor(backgroundColor);
    g.fillRect(0, 0, D.width, D.height);
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(lineStroke);

    // Axes, bounding box.
    g.setColor(Color.gray);
    g.drawLine(inset, D.height - inset, D.width - inset, D.height - inset);
    g.drawLine(D.width - inset, inset, D.width - inset, D.height - inset);
    g.drawLine(inset, inset, inset, D.height - inset);
    g.drawLine(inset, inset, D.width - inset, inset);

    double xDelta = (maxX - minX) / numIntervals;

    // X-ticks and labels.
    for (int i = 1; i <= numIntervals; i++) {
      double xTickd = i * xDelta;
      int xTick = (int) (xTickd / (maxX - minX) * (D.width - 2 * inset));
      g.drawLine(inset + xTick, D.height - inset - 5, inset + xTick, D.height - inset + 5);
      double x = minX + i * xDelta;
      g.drawString(df.format(x), xTick + inset - 5, D.height - inset + 20);
    }

    // Y-ticks
    double yDelta = (maxY - minY) / numIntervals;
    for (int i = 0; i < numIntervals; i++) {
      int yTick = (i + 1) * (int) ((D.height - 2 * inset) / (double) numIntervals);
      g.drawLine(inset - 5, D.height - yTick - inset, inset + 5, D.height - yTick - inset);
      double y = minY + (i + 1) * yDelta;
      g.drawString(df.format(y), 1, D.height - yTick - inset);
    }

    // Zoom+move
    Font savedFont = g.getFont();
    g.setFont(plusFont);
    g.drawString("+", D.width - 25, 20);
    g.setFont(minusFont);
    g.drawString("-", D.width - 25, 50);
    drawArrow(g2d, D.width - 70, 20, D.width - 70, 0, 1.0f, lineStroke); // Up
    drawArrow(g2d, D.width - 70, 30, D.width - 70, 50, 1.0f, lineStroke); // Down
    drawArrow(g2d, D.width - 65, 25, D.width - 45, 25, 1.0f, lineStroke); // Right
    drawArrow(g2d, D.width - 75, 25, D.width - 95, 25, 1.0f, lineStroke); // Left
    g.setFont(savedFont);

    // See if standard axes are in the middle.
    g.setColor(Color.gray);
    if ((minX < 0) && (maxX > 0) && (drawMiddleAxes)) {
      // Draw y-axis
      int x = (int) ((0 - minX) / (maxX - minX) * (D.width - 2 * inset));
      g.drawLine(inset + x, D.height - inset, inset + x, inset);
    }
    if ((minY < 0) && (maxY > 0) && (drawMiddleAxes)) {
      // Draw x-axis
      int y = (int) ((0 - minY) / (maxY - minY) * (D.height - 2.0 * inset));
      g.drawLine(inset, D.height - y - inset, D.width - inset, D.height - y - inset);
    }

    // Draw the objects.
    drawObjects(g, points, lines, ovals, rectangles, images, labels, eqnLines);
    if (animationMode) {
      drawObjects(g, animPoints, animLines, animOvals, animRectangles, null, labels, eqnLines);
      // No images in animation mode.
    }

    drawScribbles(g);
  }
Exemplo n.º 14
0
 public static void writeTopValue(double v) {
   writeTopString("" + df.format(v));
 }
Exemplo n.º 15
0
 static {
   form = DecimalFormat.getInstance();
   labelFont = new Font("SansSerif", Font.PLAIN, 9);
 }
Exemplo n.º 16
0
 static {
   df = new DecimalFormat();
   df.applyPattern("#.##");
 }
Exemplo n.º 17
0
 private Double roundTwoDecimals(double d) {
   DecimalFormat twoDForm = new DecimalFormat("#.##");
   return Double.valueOf(twoDForm.format(d));
 }
Exemplo n.º 18
0
  /**
   * creates a new image
   *
   * @param svgHandle a svg handle
   * @param resourceId the id of the resource from which the image will be created
   */
  protected void createNewImage(SVGHandle svgHandle, String resourceId) {

    if (svgHandle != null && resourceId != null && !resourceId.equals("")) {

      Element resourceElement = null;

      resourceElement =
          svgHandle.getScrollPane().getSVGCanvas().getDocument().getElementById(resourceId);

      final String fresourceId = resourceId;

      if (resourceElement != null) {

        final SVGHandle fhandle = svgHandle;

        // creating the canvas and setting its properties
        final JSVGCanvas canvas =
            new JSVGCanvas() {

              @Override
              public void dispose() {

                removeKeyListener(listener);
                removeMouseMotionListener(listener);
                removeMouseListener(listener);
                disableInteractions = true;
                selectableText = false;
                userAgent = null;

                bridgeContext.dispose();
                super.dispose();
              }
            };

        // the element to be added
        Element elementToAdd = null;

        canvas.setDocumentState(JSVGComponent.ALWAYS_STATIC);
        canvas.setDisableInteractions(true);

        // creating the new document
        final String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        final SVGDocument doc = (SVGDocument) resourceElement.getOwnerDocument().cloneNode(false);

        // creating the root element
        final Element root =
            (Element)
                doc.importNode(resourceElement.getOwnerDocument().getDocumentElement(), false);
        doc.appendChild(root);

        // removing all the attributes of the root element
        NamedNodeMap attributes = doc.getDocumentElement().getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {

          if (attributes.item(i) != null) {

            doc.getDocumentElement().removeAttribute(attributes.item(i).getNodeName());
          }
        }

        // adding the new attributes for the root
        root.setAttributeNS(null, "width", imageSize.width + "");
        root.setAttributeNS(null, "height", imageSize.height + "");
        root.setAttributeNS(null, "viewBox", "0 0 " + imageSize.width + " " + imageSize.height);

        // the defs element that will contain the cloned resource node
        final Element defs = (Element) doc.importNode(resourceElement.getParentNode(), true);
        root.appendChild(defs);

        if (resourceElement.getNodeName().equals("linearGradient")
            || resourceElement.getNodeName().equals("radialGradient")
            || resourceElement.getNodeName().equals("pattern")) {

          // the rectangle that will be drawn
          final Element rect = doc.createElementNS(svgNS, "rect");
          rect.setAttributeNS(null, "x", "0");
          rect.setAttributeNS(null, "y", "0");
          rect.setAttributeNS(null, "width", imageSize.width + "");
          rect.setAttributeNS(null, "height", imageSize.height + "");

          elementToAdd = rect;

          // setting that the rectangle uses the resource
          String id = resourceElement.getAttribute("id");

          if (id == null) {

            id = "";
          }

          rect.setAttributeNS(null, "style", "fill:url(#" + id + ");");

          // getting the cloned resource node
          Node cur = null;
          Element clonedResourceElement = null;
          String id2 = "";

          for (cur = defs.getFirstChild(); cur != null; cur = cur.getNextSibling()) {

            if (cur instanceof Element) {

              id2 = ((Element) cur).getAttribute("id");

              if (id2 != null && id.equals(id2)) {

                clonedResourceElement = (Element) cur;
              }
            }
          }

          if (clonedResourceElement != null) {

            // getting the root element of the initial resource
            // element
            Element initialRoot = resourceElement.getOwnerDocument().getDocumentElement();

            // getting the width and height of the initial root
            // element
            double initialWidth = 0, initialHeight = 0;

            try {
              initialWidth =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "width"));
              initialHeight =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "height"));
            } catch (DOMException ex) {
              ex.printStackTrace();
            }

            if (resourceElement.getNodeName().equals("linearGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  x1 = Double.parseDouble(resourceElement.getAttributeNS(null, "x1"));
                  y1 = Double.parseDouble(resourceElement.getAttributeNS(null, "y1"));
                  x2 = Double.parseDouble(resourceElement.getAttributeNS(null, "x2"));
                  y2 = Double.parseDouble(resourceElement.getAttributeNS(null, "y2"));

                  x1 = x1 / initialWidth * imageSize.width;
                  y1 = y1 / initialHeight * imageSize.height;
                  x2 = x2 / initialWidth * imageSize.width;
                  y2 = y2 / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x1", format.format(x1));
                clonedResourceElement.setAttributeNS(null, "y1", format.format(y1));
                clonedResourceElement.setAttributeNS(null, "x2", format.format(x2));
                clonedResourceElement.setAttributeNS(null, "y2", format.format(y2));
              }

            } else if (resourceElement.getNodeName().equals("radialGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double cx = 0, cy = 0, r = 0, fx = 0, fy = 0;

                // normalizing the values for the circle to fit
                // the rectangle
                try {
                  cx = Double.parseDouble(resourceElement.getAttributeNS(null, "cx"));
                  cy = Double.parseDouble(resourceElement.getAttributeNS(null, "cy"));
                  r = Double.parseDouble(resourceElement.getAttributeNS(null, "r"));
                  fx = Double.parseDouble(resourceElement.getAttributeNS(null, "fx"));
                  fy = Double.parseDouble(resourceElement.getAttributeNS(null, "fy"));

                  cx = cx / initialWidth * imageSize.width;
                  cy = cy / initialHeight * imageSize.height;

                  r =
                      r
                          / (Math.abs(
                              Math.sqrt(Math.pow(initialWidth, 2) + Math.pow(initialHeight, 2))))
                          * Math.abs(
                              Math.sqrt(
                                  Math.pow(imageSize.width, 2) + Math.pow(imageSize.width, 2)));

                  fx = fx / initialWidth * imageSize.width;
                  fy = fy / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "cx", format.format(cx));
                clonedResourceElement.setAttributeNS(null, "cy", format.format(cy));
                clonedResourceElement.setAttributeNS(null, "r", format.format(r));
                clonedResourceElement.setAttributeNS(null, "fx", format.format(fx));
                clonedResourceElement.setAttributeNS(null, "fy", format.format(fy));
              }

            } else if (resourceElement.getNodeName().equals("pattern")) {

              if (resourceElement.getAttributeNS(null, "patternUnits").equals("userSpaceOnUse")) {

                double x = 0, y = 0, w = 0, h = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  String xString = resourceElement.getAttributeNS(null, "x");
                  if (!xString.equals("")) {
                    x = Double.parseDouble(xString);
                  }
                  String yString = resourceElement.getAttributeNS(null, "y");
                  if (!yString.equals("")) {
                    y = Double.parseDouble(yString);
                  }
                  String wString = resourceElement.getAttributeNS(null, "w");
                  if (!wString.equals("")) {
                    w = Double.parseDouble(wString);
                  }
                  String hString = resourceElement.getAttributeNS(null, "h");
                  if (!hString.equals("")) {
                    h = Double.parseDouble(hString);
                  }

                  x = x / initialWidth * imageSize.width;
                  y = y / initialHeight * imageSize.height;
                  w = w / initialWidth * imageSize.width;
                  h = h / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x", format.format(x));
                clonedResourceElement.setAttributeNS(null, "y", format.format(y));
                clonedResourceElement.setAttributeNS(null, "width", format.format(w));
                clonedResourceElement.setAttributeNS(null, "height", format.format(h));
              }
            }
          }

        } else if (resourceElement.getNodeName().equals("marker")) {

          // the line that will be drawn
          final Element line = doc.createElementNS(svgNS, "line");
          line.setAttributeNS(null, "x1", (((double) imageSize.width) / 2) + "");
          line.setAttributeNS(null, "y1", (((double) imageSize.height) / 2) + "");
          line.setAttributeNS(null, "x2", ((double) imageSize.width / 2) + "");
          line.setAttributeNS(null, "y2", imageSize.height + "");

          elementToAdd = line;

          // setting that the line uses the resource
          String id = resourceElement.getAttribute("id");
          if (id == null) id = "";
          line.setAttributeNS(
              null, "style", "stroke:none;fill:none;marker-start:url(#" + id + ");");
        }

        root.appendChild(elementToAdd);

        // adding a rendering listener to the canvas
        GVTTreeRendererAdapter gVTTreeRendererAdapter =
            new GVTTreeRendererAdapter() {

              @Override
              public void gvtRenderingCompleted(GVTTreeRendererEvent evt) {

                Image bufferedImage = canvas.getOffScreen();

                if (bufferedImage != null) {

                  Graphics g = bufferedImage.getGraphics();
                  Color borderColor = MetalLookAndFeel.getSeparatorForeground();

                  g.setColor(borderColor);
                  g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
                }

                setImage(fhandle, fresourceId, bufferedImage);

                // refreshing the panels that have been created when no
                // image was available for them
                Image image = null;

                for (ResourceRepresentation resourceRepresentation :
                    new LinkedList<ResourceRepresentation>(resourceRepresentationList)) {

                  if (resourceRepresentation != null) {

                    resourceRepresentation.refreshRepresentation();
                    image = resourceRepresentation.getImage();

                    if (image != null) {

                      resourceRepresentationList.remove(resourceRepresentation);
                    }
                  }
                }

                canvas.removeGVTTreeRendererListener(this);
                canvas.stopProcessing();
                canvas.dispose();
              }
            };

        canvas.addGVTTreeRendererListener(gVTTreeRendererAdapter);

        // setting the document for the canvas
        canvas.setSVGDocument(doc);

        canvas.setBackground(Color.white);
        canvas.setBounds(1, 1, imageSize.width, imageSize.height);
      }
    }
  }
Exemplo n.º 19
0
 void print(String name, Vec value) {
   g.drawString(name + ":" + df.format(value.x) + " , " + df.format(value.y), x, y += 20);
 }
Exemplo n.º 20
0
 /** convenience method for setting a double field */
 public static void setFieldValue(JTextField field, double value) {
   DecimalFormat formatter = new DecimalFormat("0.0##E0");
   field.setText(formatter.format(value));
 }
Exemplo n.º 21
0
 public static String format(double value) {
   return df.format(value);
 }