public String nextToken() {
      StringBuffer token = new StringBuffer();

      while (skipChar((char) getChar(1))) {
        nextChar();
      }

      while (nextChar()) {
        char c = getChar();

        if (c == '"') {
          token.append(parseString());
          break;
        }

        if (isWordChar(c)) {
          token.append(c);
        } else {
          if (token.length() == 0) token.append(c);
          else position--;
          break;
        }
      }

      if (token.length() == 0) return null;
      else return token.toString();
    }
Example #2
0
File: Chat.java Project: brgj/Tales
 /**
  * Send a message to the client
  *
  * @return true if message is not empty
  */
 public boolean sendMessage() {
   if (messageToSend.length() == 0) return false;
   client.sendMessage(messageToSend.toString());
   addMessageToLog("You: " + messageToSend.toString());
   messageToSend.delete(0, messageToSend.length());
   return true;
 }
  public GElement generateGraph(String dotFile) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(dotFile));
    graph = null;

    /**
     * The problem here is that DOT sometime inserts a '\' at the end of a long line so we have to
     * skip it and continue to parse until a "real" EOL is reached. Example: statement ->
     * compoundStatement [pos="e,3264,507 3271,2417 3293,2392 ... 3237,565 3234,560 32\ 39,545
     * 3243,534 3249,523 3257,514"];
     */
    StringBuffer line = new StringBuffer();
    int c; // current character
    int pc = -1; // previous character
    while ((c = br.read()) != -1) {
      if (c == '\n') {
        if (pc == '\\') {
          // Remove the last \ if it was part of the DOT wrapping character
          line.deleteCharAt(line.length() - 1);
        } else {
          GElement element = parseLine(line.toString());
          if (element != null) {
            if (graph == null) graph = element;
            else graph.addElement(element);
          }
          line.delete(0, line.length());
        }
      } else if (c != '\r') {
        line.append((char) c);
      }
      pc = c;
    }
    return graph;
  }
Example #4
0
 /**
  * Reads a line of text edited by the user, terminated by <code>ENTER</code>. Editing is performed
  * at the current cursor position.
  *
  * @param field Maximum length of the text
  * @return The text read. <code>null</code> if it was pressed the <code>Esc</code> key.
  */
 public static String nextLine(int field) {
   boolean oldCursorOn = frame.isCursorOn();
   boolean oldEcho = frame.isEcho();
   cursor(false);
   int lin = frame.getLin(), col = frame.getCol();
   for (int i = 0; i < field; ++i) print(' ');
   cursor(lin, col);
   cursor(true);
   echo(false);
   StringBuffer res = new StringBuffer(field);
   char c;
   while ((c = waitChar(0)) != '\n') {
     if (c == KeyEvent.VK_ESCAPE) {
       res = null;
       break;
     } // Esc (27)
     else if (c == KeyEvent.VK_BACK_SPACE) { // Backspace (8)
       if (res.length() == 0) continue;
       res.deleteCharAt(res.length() - 1);
       cursor(false);
       cursor(frame.getLin(), frame.getCol() - 1);
       print(' ');
       cursor(frame.getLin(), frame.getCol() - 1);
       cursor(true);
     } else if (res.length() < field) {
       print(c);
       res.append(c);
     }
   }
   cursor(oldCursorOn);
   echo(oldEcho);
   return res == null ? null : res.toString();
 }
    private void setCoordsText(final Coord[] coords, String description) {
      StringBuffer linebuf;
      Coord vertex;
      YaxisTreeNode node;
      TreeNode[] nodes;
      Integer lineID;
      double duration;
      int coords_length;
      int idx, ii;

      linebuf = new StringBuffer();
      coords_length = coords.length;
      if (coords_length > 1) {
        duration = coords[coords_length - 1].time - coords[0].time;
        linebuf.append("duration" + description + " = " + tfmt.format(duration));
        if (num_cols < linebuf.length()) num_cols = linebuf.length();
        num_rows++;
        strbuf.append(linebuf.toString() + "\n");
      }
      for (idx = 0; idx < coords_length; idx++) {
        linebuf = new StringBuffer("[" + idx + "]: ");
        vertex = coords[idx];
        lineID = new Integer(vertex.lineID);
        node = (YaxisTreeNode) map_line2treenodes.get(lineID);
        nodes = node.getPath();
        linebuf.append("time" + description + " = " + fmt.format(vertex.time));
        for (ii = 1; ii < nodes.length; ii++)
          linebuf.append(", " + y_colnames[ii - 1] + " = " + nodes[ii]);
        if (num_cols < linebuf.length()) num_cols = linebuf.length();
        num_rows++;
        strbuf.append(linebuf.toString());
        if (idx < coords_length - 1) strbuf.append("\n");
      }
    }
  /**
   * Constructs a new path from current user path. This is an easy way to get a path if the user
   * specified, for example, "..\Java" as new path. This method will return the argument if this one
   * is a path to a root (i.e, if <code>change</code> is equal to C:\Jdk, constructPath will return
   * C:\Jdk).
   *
   * @param change The modification to apply to the path
   */
  public static String constructPath(String change) {
    if (beginsWithRoot(change)) return change;

    StringBuffer newPath = new StringBuffer(getUserDirectory());

    char current;
    char lastChar = '\0';
    boolean toAdd = false;
    change = change.trim();
    StringBuffer buf = new StringBuffer(change.length());

    for (int i = 0; i < change.length(); i++) {
      switch ((current = change.charAt(i))) {
        case '.':
          if (lastChar == '.') {
            String parent = (new File(newPath.toString())).getParent();
            if (parent != null) newPath = new StringBuffer(parent);
          } else if ((lastChar != '\0' && lastChar != '\\' && lastChar != '/')
              || (i < change.length() - 1 && change.charAt(i + 1) != '.')) buf.append('.');
          lastChar = '.';
          break;
        case '\\':
        case '/':
          if (lastChar == '\0') {
            newPath = new StringBuffer(getRoot(newPath.toString()));
          } else {
            char c = newPath.charAt(newPath.length() - 1);
            if (c != '\\' && c != '/') newPath.append(File.separator).append(buf.toString());
            else newPath.append(buf.toString());
            buf = new StringBuffer();
            toAdd = false;
          }
          lastChar = '\\';
          break;
        case '~':
          if (i < change.length() - 1) {
            if (change.charAt(i + 1) == '\\' || change.charAt(i + 1) == '/')
              newPath = new StringBuffer(getHomeDirectory());
            else buf.append('~');
          } else if (i == 0) newPath = new StringBuffer(getHomeDirectory());
          else buf.append('~');
          lastChar = '~';
          break;
        default:
          lastChar = current;
          buf.append(current);
          toAdd = true;
          break;
      }
    }

    if (toAdd) {
      char c = newPath.charAt(newPath.length() - 1);
      if (c != '\\' && c != '/') newPath.append(File.separator).append(buf.toString());
      else newPath.append(buf.toString());
    }

    return newPath.toString();
  }
Example #7
0
 /**
  * A utility method to make a name=value part of the adde request string
  *
  * @param buf The buffer to append to
  * @param name The property name
  * @param value The value
  */
 protected void appendKeyValue(StringBuffer buf, String name, String value) {
   if ((buf.length() == 0) || (buf.charAt(buf.length() - 1) != '?')) {
     buf.append("&");
   }
   buf.append(name);
   buf.append("=");
   buf.append(value);
 }
Example #8
0
 public TextState copyAll() {
   TextState tmp = copyState();
   if (s.length() == 0) return tmp;
   for (int i = 0; i < s.length(); i++) {
     tmp.s.append(s.charAt(i));
   }
   return tmp;
 }
Example #9
0
  private void onReceiveChar(char character) {

    buffer.append(character);

    if (buffer.charAt(buffer.length() - 1) == '\n') {
      onReceiveLine(buffer.toString());
      buffer.delete(0, buffer.length());
    }
  }
  /**
   * Output the specified {@link Collection} in proper columns.
   *
   * @param stuff the stuff to print
   */
  public void printColumns(final Collection stuff) throws IOException {
    if ((stuff == null) || (stuff.size() == 0)) {
      return;
    }

    int width = getTermwidth();
    int maxwidth = 0;

    for (Iterator i = stuff.iterator();
        i.hasNext();
        maxwidth = Math.max(maxwidth, i.next().toString().length())) {;
    }

    StringBuffer line = new StringBuffer();

    int showLines;

    if (usePagination) showLines = getTermheight() - 1; // page limit
    else showLines = Integer.MAX_VALUE;

    for (Iterator i = stuff.iterator(); i.hasNext(); ) {
      String cur = (String) i.next();

      if ((line.length() + maxwidth) > width) {
        printString(line.toString().trim());
        printNewline();
        line.setLength(0);
        if (--showLines == 0) { // Overflow
          printString(loc.getString("display-more"));
          flushConsole();
          int c = readVirtualKey();
          if (c == '\r' || c == '\n') showLines = 1; // one step forward
          else if (c != 'q') showLines = getTermheight() - 1; // page forward

          back(loc.getString("display-more").length());
          if (c == 'q') break; // cancel
        }
      }

      pad(cur, maxwidth + 3, line);
    }

    if (line.length() > 0) {
      printString(line.toString().trim());
      printNewline();
      line.setLength(0);
    }
  }
Example #11
0
 private static void uppercaseFirstLetter(final StringBuffer buf) {
   if (buf.length() > 1) {
     char[] firstLetter = new char[1];
     buf.getChars(0, 1, firstLetter, 0);
     buf.setCharAt(0, Character.toUpperCase(firstLetter[0]));
   }
 }
    /**
     * Create a Transferable to use as the source for a data transfer.
     *
     * @param c The component holding the data to be transfered. This argument is provided to enable
     *     sharing of TransferHandlers by multiple components.
     * @return The representation of the data to be transfered.
     */
    protected Transferable createTransferable(JComponent c) {
      Object[] values = null;
      if (c instanceof JList) {
        values = ((JList) c).getSelectedValues();
      } else if (c instanceof JTable) {
        JTable table = (JTable) c;
        int[] rows = table.getSelectedRows();
        if (rows != null) {
          values = new Object[rows.length];
          for (int i = 0; i < rows.length; i++) {
            values[i] = table.getValueAt(rows[i], 0);
          }
        }
      }
      if (values == null || values.length == 0) {
        return null;
      }

      StringBuffer plainBuf = new StringBuffer();
      StringBuffer htmlBuf = new StringBuffer();

      htmlBuf.append("<html>\n<body>\n<ul>\n");

      for (Object obj : values) {
        String val = ((obj == null) ? "" : obj.toString());
        plainBuf.append(val + "\n");
        htmlBuf.append("  <li>" + val + "\n");
      }

      // remove the last newline
      plainBuf.deleteCharAt(plainBuf.length() - 1);
      htmlBuf.append("</ul>\n</body>\n</html>");

      return new FileTransferable(plainBuf.toString(), htmlBuf.toString(), values);
    }
Example #13
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  public String toString() {
    StringBuffer b = new StringBuffer();
    b.append("ID:" + id);
    b.append("\tName:" + name);
    b.append("\tSex:" + sex + "\n");
    b.append("\tAffected:" + affection + "\n");

    if (mother == null) {
      b.append("\tMother: null");
    } else {
      b.append("\tMother:" + mother.id);
    }

    if (father == null) {
      b.append("\tFather: null");
    } else {
      b.append("\tFather:" + father.id);
    }

    b.append("\tChildren:");
    Vector<PelicanPerson> children = getChildren();
    if (children.size() > 0) {
      Iterator<PelicanPerson> it = children.iterator();
      while (it.hasNext()) {
        PelicanPerson p = it.next();
        b.append(p.id + ",");
      }
      b.deleteCharAt(b.length() - 1);
    } else {
      b.append("none");
    }
    b.append("\n");
    return b.toString();
  }
    // For Shadow Primitive
    public void setShadowText(final Shadow shade, final Category type) {
      this.setEndCoordsText(
          shade.getStartVertex(),
          shade.getFinalVertex(),
          shade.getEarliestTime(),
          shade.getLatestTime(),
          shade.getVertices().length);
      strbuf.append("\n\n");
      this.setCoordsText(shade.getVertices(), " (ave)");
      strbuf.append("\n");

      StringBuffer linebuf;
      Topology shade_topo;
      CategoryWeight[] twgts;
      CategoryWeight twgt;
      String twgt_str;
      int print_status;
      int idx;

      shade_topo = shade.getCategory().getTopology();

      // linebuf = new StringBuffer( "Number of Real Drawables = " );
      linebuf = new StringBuffer("Number of Real ");
      linebuf.append(shade_topo + "s = ");
      linebuf.append(shade.getNumOfRealObjects());
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append("\n" + linebuf.toString());
      strbuf.append("\n");

      print_status = getPrintStatus(shade_topo);
      strbuf.append("\n" + CategoryWeight.getPrintTitle(print_status));
      twgts = shade.arrayOfCategoryWeights();
      for (idx = 0; idx < twgts.length; idx++) {
        twgt = twgts[idx];
        twgt_str = twgt.toInfoBoxString(print_status);
        if (twgt.getCategory().equals(type)) {
          twgt_str += "  <---";
          if (num_cols < twgt_str.length() + 6) num_cols = twgt_str.length() + 6;
        } else {
          if (num_cols < twgt_str.length()) num_cols = twgt_str.length();
        }
        num_rows++;
        strbuf.append("\n" + twgt_str);
      }
    }
Example #16
0
  public TextLocation findWordsRightEdge(TextLocation location) {

    for (int i = location.toIndex(getLines()); i <= text.length() - 1; i++) {
      if (i == 0) i = 1;
      if (isAtEndOfWord(i)) return TextLocation.fromIndex(getLines(), i);
    }
    return getEndLocation();
  }
Example #17
0
  public synchronized void setText(String newText) {
    if (newText == null) newText = "";

    if (newText.length() == text.length() && newText.equals(getText())) return;

    text = new StringBuffer(newText);
    clearCache();
    setCaretLocation(getEndLocation());
  }
Example #18
0
  private static void checkXmlGregorianCalendarFieldRef(QName type, XMLGregorianCalendar cal)
      throws javax.xml.bind.MarshalException {
    StringBuffer buf = new StringBuffer();
    int bitField = xmlGregorianCalendarFieldRef.get(type);
    final int l = 0x1;
    int pos = 0;
    while (bitField != 0x0) {
      int bit = bitField & l;
      bitField >>>= 4;
      pos++;

      if (bit == 1) {
        switch (pos) {
          case 1:
            if (cal.getSecond() == DatatypeConstants.FIELD_UNDEFINED) {
              buf.append("  " + Messages.XMLGREGORIANCALENDAR_SEC);
            }
            break;
          case 2:
            if (cal.getMinute() == DatatypeConstants.FIELD_UNDEFINED) {
              buf.append("  " + Messages.XMLGREGORIANCALENDAR_MIN);
            }
            break;
          case 3:
            if (cal.getHour() == DatatypeConstants.FIELD_UNDEFINED) {
              buf.append("  " + Messages.XMLGREGORIANCALENDAR_HR);
            }
            break;
          case 4:
            if (cal.getDay() == DatatypeConstants.FIELD_UNDEFINED) {
              buf.append("  " + Messages.XMLGREGORIANCALENDAR_DAY);
            }
            break;
          case 5:
            if (cal.getMonth() == DatatypeConstants.FIELD_UNDEFINED) {
              buf.append("  " + Messages.XMLGREGORIANCALENDAR_MONTH);
            }
            break;
          case 6:
            if (cal.getYear() == DatatypeConstants.FIELD_UNDEFINED) {
              buf.append("  " + Messages.XMLGREGORIANCALENDAR_YEAR);
            }
            break;
          case 7: // ignore timezone setting
            break;
        }
      }
    }
    if (buf.length() > 0) {
      throw new javax.xml.bind.MarshalException(
          Messages.XMLGREGORIANCALENDAR_INVALID.format(type.getLocalPart()) + buf.toString());
    }
  }
  private String createPropertiesString() {
    final StringBuffer buffer = new StringBuffer();
    for (final String property : myValues) {
      if (buffer.length() == 0) {
        buffer.append(property);
      } else {
        buffer.append(',');
        buffer.append(property);
      }
    }

    return buffer.toString();
  }
  private void changed() {

    double price = 1.0500;
    double spread = 0.0004;

    CandleDataPoint candle = new CandleDataPoint();
    candle.setInstrument(Instrument.AUDUSD);
    candle.setPeriod(Period.FifteenMin);

    double low = price;
    double high = price + sldSize.getValue() / 10000.0;
    double open = price + sldSize.getValue() * (sldOpen.getValue() / 100.0) / 10000.0;
    double close = price + sldSize.getValue() * (sldClose.getValue() / 100.0) / 10000.0;

    candle.setBuyOpen(open - spread);
    candle.setSellOpen(open + spread);
    candle.setBuyClose(close - spread);
    candle.setSellClose(close + spread);
    candle.setBuyHigh(high - spread);
    candle.setSellHigh(high + spread);
    candle.setBuyLow(low - spread);
    candle.setSellLow(low + spread);

    StringBuffer buf =
        new StringBuffer(
            String.format(
                "%.4f / %.4f / %.4f / %.4f %n",
                candle.getOpen(), candle.getHigh(), candle.getLow(), candle.getClose()));

    for (CandleType candleType : CandleType.values()) {
      if (candleType.is(candle)) {
        buf.append(candleType.toString()).append(", ");
      }
    }

    if (buf.length() > 2) txt.setText(buf.substring(0, buf.length() - 2));
    else txt.setText("None");
  }
Example #21
0
 String toBinary(int n) {
   if (n == 0) {
     return ("0");
   }
   StringBuffer binary = new StringBuffer();
   while (n > 0) {
     int rem = n % 2;
     binary = new StringBuffer(rem + binary.toString());
     n = n / 2;
   }
   while (binary.length() < 8) {
     binary.insert(0, "0");
   }
   return binary.toString();
 }
Example #22
0
 private static String readln(InputStream s) {
   try {
     int c;
     StringBuffer sb = new StringBuffer();
     while ((c = s.read()) > 0 && c != 255 && (c == '\n' || c == '\r'))
       ; // Skip carriage returns and line feeds
     while (c > 0 && c != 255 && c != '\n' && c != '\r') {
       sb.append((char) c);
       c = s.read();
     }
     if ((c == -1 || c == 255) && sb.length() == 0) return null;
     return new String(sb);
   } catch (IOException e) {
     return null;
   }
 }
Example #23
0
  /**
   * Method description
   *
   * @param color
   * @return
   */
  public static String getcommaSeparatedRGBString(Color color) {

    if (color != null) {

      scratchBuffer.delete(0, scratchBuffer.length()); // Clear
      int red = color.getRed();
      int green = color.getGreen();
      int blue = color.getBlue();
      scratchBuffer.append(red);
      scratchBuffer.append(",");
      scratchBuffer.append(green);
      scratchBuffer.append(",");
      scratchBuffer.append(blue);
    }
    return scratchBuffer.toString();
  }
Example #24
0
  private void doAssert(Map<String, String> expected, PlaybackRunner.StatusCallback cb)
      throws AssertionError {
    final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

    if (owner == null) {
      throw new AssertionError("No component focused");
    }

    Component eachParent = owner;
    final LinkedHashMap<String, String> actual = new LinkedHashMap<String, String>();
    while (eachParent != null) {
      if (eachParent instanceof TestableUi) {
        ((TestableUi) eachParent).putInfo(actual);
      }

      eachParent = eachParent.getParent();
    }

    Set testedKeys = new LinkedHashSet<String>();
    for (String eachKey : expected.keySet()) {
      testedKeys.add(eachKey);

      final String actualValue = actual.get(eachKey);
      final String expectedValue = expected.get(eachKey);

      if (!expectedValue.equals(actualValue)) {
        throw new AssertionError(
            eachKey + " expected: " + expectedValue + " but was: " + actualValue);
      }
    }

    Map<String, String> untested = new HashMap<String, String>();
    for (String eachKey : actual.keySet()) {
      if (testedKeys.contains(eachKey)) continue;
      untested.put(eachKey, actual.get(eachKey));
    }

    StringBuffer untestedText = new StringBuffer();
    for (String each : untested.keySet()) {
      if (untestedText.length() > 0) {
        untestedText.append(",");
      }
      untestedText.append(each).append("=").append(untested.get(each));
    }

    cb.message("Untested info: " + untestedText.toString(), getLine());
  }
Example #25
0
 /**
  * Generates the CIDFontTyte2 dictionary.
  *
  * @param fontDescriptor the indirect reference to the font descriptor
  * @param subsetPrefix the subset prefix
  * @param metrics the horizontal width metrics
  * @return a stream
  */
 public PdfDictionary getCIDFontType2(
     PdfIndirectReference fontDescriptor, String subsetPrefix, Object metrics[]) {
   PdfDictionary dic = new PdfDictionary(PdfName.FONT);
   // sivan; cff
   if (cff) {
     dic.put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE0);
     dic.put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + "-" + encoding));
   } else {
     dic.put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE2);
     dic.put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
   }
   dic.put(PdfName.FONTDESCRIPTOR, fontDescriptor);
   if (!cff) dic.put(PdfName.CIDTOGIDMAP, PdfName.IDENTITY);
   PdfDictionary cdic = new PdfDictionary();
   cdic.put(PdfName.REGISTRY, new PdfString("Adobe"));
   cdic.put(PdfName.ORDERING, new PdfString("Identity"));
   cdic.put(PdfName.SUPPLEMENT, new PdfNumber(0));
   dic.put(PdfName.CIDSYSTEMINFO, cdic);
   if (!vertical) {
     dic.put(PdfName.DW, new PdfNumber(1000));
     StringBuffer buf = new StringBuffer("[");
     int lastNumber = -10;
     boolean firstTime = true;
     for (int k = 0; k < metrics.length; ++k) {
       int metric[] = (int[]) metrics[k];
       if (metric[1] == 1000) continue;
       int m = metric[0];
       if (m == lastNumber + 1) {
         buf.append(' ').append(metric[1]);
       } else {
         if (!firstTime) {
           buf.append(']');
         }
         firstTime = false;
         buf.append(m).append('[').append(metric[1]);
       }
       lastNumber = m;
     }
     if (buf.length() > 1) {
       buf.append("]]");
       dic.put(PdfName.W, new PdfLiteral(buf.toString()));
     }
   }
   return dic;
 }
  // Generate css-file
  private String generateCssStyles(String param) {
    String sessionId;
    if (!param.contains("sessionid")) {
      return "";
    }
    sessionId = param.substring(param.indexOf("sessionid=") + 10);

    Map<MyTextAttributes, Integer> mapAttributes = mapCss.get(Integer.parseInt(sessionId));
    StringBuffer buffer = new StringBuffer();
    buffer.append(
        "body { font-family: monospace; font-size: 12px; color: #000000; background-color: #FFFFFF;} ");
    buffer.append(
        " a {text-decoration: none; color: #000000;} span.highlighting { background-color: yellow !important;}");
    buffer.append(
        " a span {text-decoration: none; color: #000000;} a:hover span {color: blue; text-decoration: underline;}");
    if (mapAttributes != null) {
      for (MyTextAttributes attr : mapAttributes.keySet()) {
        buffer.append("\nspan.class");
        buffer.append(mapAttributes.get(attr)).append("{");
        String tmp = MyBaseHandler.getColor(attr.getForegroundColor());
        if (!tmp.equals("#000000")) {
          buffer.append("color: ").append(tmp).append("; ");
        }
        tmp = MyBaseHandler.getColor(attr.getBackgroundColor());
        if (!tmp.equals("#ffffff")) {
          buffer.append("background-color: ").append(tmp).append("; ");
        }
        buffer.append(MyBaseHandler.getFontType(attr.getFontType())).append(" ");
        if (attr.getEffectType().equals(EffectType.LINE_UNDERSCORE)) {
          buffer.append("text-decoration: underline; ").append("; ");
        }
        buffer.append("}");

        // Cut empty styles
        tmp = "\nspan.class" + mapAttributes.get(attr) + "{ }";
        int position = buffer.toString().indexOf(tmp);
        if (position != -1) {
          buffer = buffer.delete(position, buffer.length());
        }
      }
    }
    return buffer.toString();
  }
    /*
     * When user leaves a cell after editing it, the contents of
     * that cell need to be converted from a string into an
     * object of the appropriate type before updating the table.
     * However, when the call comes from the Popup window, the data
     * has already been converted and validated.
     * We assume that a String being passed in here is a value from
     * a text field that needs to be converted to an object, and
     * a non-string object has already been validated and converted.
     */
    public void setValueAt(Object newValueString, int row, int col) {
      if (!(newValueString instanceof java.lang.String)) {
        // data is an object - assume already validated
        super.setValueAt(newValueString, row, col);
        return;
      }

      // data is a String, so we need to convert to real object
      StringBuffer messageBuffer = new StringBuffer();

      int modelIndex = getColumnModel().getColumn(col).getModelIndex();
      ColumnDisplayDefinition colDef = getColumnDefinitions()[modelIndex];
      Object newValueObject =
          CellComponentFactory.validateAndConvert(
              colDef, getValueAt(row, col), (String) newValueString, messageBuffer);

      if (messageBuffer.length() > 0) {

        // i18n[dataSetViewerTablePanel.textCantBeConverted=The given text cannot be converted into
        // the internal object.\nThe database has not been changed.\nThe conversion error was:\n{0}]
        String msg =
            s_stringMgr.getString("dataSetViewerTablePanel.textCantBeConverted", messageBuffer);

        if (s_log.isDebugEnabled()) {
          s_log.debug("setValueAt: msg from DataTypeComponent was: " + msg);
        }

        // display error message and do not update the table
        JOptionPane.showMessageDialog(
            this,
            msg,
            // i18n[dataSetViewerTablePanel.conversionError=Conversion Error]
            s_stringMgr.getString("dataSetViewerTablePanel.conversionError"),
            JOptionPane.ERROR_MESSAGE);

      } else {
        // data converted ok, so update the table
        super.setValueAt(newValueObject, row, col);
      }
    }
    private void setEndCoordsText(
        final Coord start_vtx,
        final Coord final_vtx,
        double earliest_time,
        double latest_time,
        int coords_length) {
      StringBuffer linebuf;
      Coord vertex;
      YaxisTreeNode node;
      TreeNode[] nodes;
      Integer lineID;
      double duration;
      int idx, ii;

      duration = latest_time - earliest_time;
      linebuf = new StringBuffer();
      linebuf.append("duration (max) = " + tfmt.format(duration));
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append(linebuf.toString());

      idx = 0;
      linebuf = new StringBuffer("[" + idx + "]: ");
      vertex = start_vtx;
      lineID = new Integer(vertex.lineID);
      node = (YaxisTreeNode) map_line2treenodes.get(lineID);
      nodes = node.getPath();
      linebuf.append("time (min) = " + fmt.format(earliest_time));
      for (ii = 1; ii < nodes.length; ii++)
        linebuf.append(", " + y_colnames[ii - 1] + " = " + nodes[ii]);
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append("\n" + linebuf.toString());

      idx = coords_length - 1;
      linebuf = new StringBuffer("[" + idx + "]: ");
      vertex = final_vtx;
      lineID = new Integer(vertex.lineID);
      node = (YaxisTreeNode) map_line2treenodes.get(lineID);
      nodes = node.getPath();
      linebuf.append("time (max) = " + fmt.format(latest_time));
      for (ii = 1; ii < nodes.length; ii++)
        linebuf.append(", " + y_colnames[ii - 1] + " = " + nodes[ii]);
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append("\n" + linebuf.toString());
    }
 /** @noinspection ALL */
 private void $$$loadLabelText$$$(JLabel component, String text) {
   StringBuffer result = new StringBuffer();
   boolean haveMnemonic = false;
   char mnemonic = '\0';
   int mnemonicIndex = -1;
   for (int i = 0; i < text.length(); i++) {
     if (text.charAt(i) == '&') {
       i++;
       if (i == text.length()) break;
       if (!haveMnemonic && text.charAt(i) != '&') {
         haveMnemonic = true;
         mnemonic = text.charAt(i);
         mnemonicIndex = result.length();
       }
     }
     result.append(text.charAt(i));
   }
   component.setText(result.toString());
   if (haveMnemonic) {
     component.setDisplayedMnemonic(mnemonic);
     component.setDisplayedMnemonicIndex(mnemonicIndex);
   }
 }
Example #30
0
  /**
   * This method inserts a blank character between to consecutive newline characters if encoutered.
   * Also appends a blank character at the beginning of the text, if the first character is a
   * newline character and at the end of the text, if the last character is also a newline. This is
   * useful when trying to layout the paragraphs. Thanks to Teodor Danciu for this this method (c)
   * 2003 Teodor Danciu
   */
  public static String treatNewLineChars(String source) {
    String result = source;

    if (source != null && source.length() > 0) {
      StringBuffer sbuffer = new StringBuffer(source);

      // insert a blank character between every two consecutives
      // newline characters
      int offset = source.length() - 1;
      int pos = source.lastIndexOf("\n\n", offset);
      while (pos >= 0 && offset > 0) {
        sbuffer = sbuffer.insert(pos + 1, " ");
        offset = pos - 1;
        pos = source.lastIndexOf("\n\n", offset);
      }

      // append a blank character at the and of the text
      // if the last character is a newline character
      if (sbuffer.charAt(sbuffer.length() - 1) == '\n') {
        sbuffer.append(' ');
      }

      // append a blank character at the begining of the text
      // if the first character is a newline character
      if (sbuffer.charAt(0) == '\n') {
        sbuffer.insert(0, ' ');
      }

      result = sbuffer.toString();
    }

    // remove this if you want to treat the tab characters in a special way
    result = replaceTabWithBlank(result);

    return result;
  }