Esempio n. 1
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);
    }
Esempio n. 2
0
 private String bigIntToHexString(BigInteger bi) {
   StringBuffer buf = new StringBuffer();
   buf.append("0x");
   String val = bi.toString(16);
   for (int i = 0; i < ((2 * addressSize) - val.length()); i++) {
     buf.append('0');
   }
   buf.append(val);
   return buf.toString();
 }
  /**
   * Return the number of characters that will be printed when the specified character is echoed to
   * the screen. Adapted from cat by Torbjorn Granlund, as repeated in stty by David MacKenzie.
   */
  StringBuffer getPrintableCharacters(char ch) {
    StringBuffer sbuff = new StringBuffer();

    if (ch >= 32) {
      if (ch < 127) {
        sbuff.append(ch);
      } else if (ch == 127) {
        sbuff.append('^');
        sbuff.append('?');
      } else {
        sbuff.append('M');
        sbuff.append('-');

        if (ch >= (128 + 32)) {
          if (ch < (128 + 127)) {
            sbuff.append((char) (ch - 128));
          } else {
            sbuff.append('^');
            sbuff.append('?');
          }
        } else {
          sbuff.append('^');
          sbuff.append((char) (ch - 128 + 64));
        }
      }
    } else {
      sbuff.append('^');
      sbuff.append((char) (ch + 64));
    }

    return sbuff;
  }
Esempio n. 4
0
 /**
  * This method is activated on the Keystrokes we are listening to in this implementation. Here it
  * listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in
  * invalid selection and then copy action cannot be performed. Paste is done by aligning the upper
  * left corner of the selection with the 1st element in the current selection of the JTable.
  */
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().compareTo("Copy") == 0) {
     StringBuffer sbf = new StringBuffer();
     // Check to ensure we have selected only a contiguous block of
     // cells
     int numcols = jTable1.getSelectedColumnCount();
     int numrows = jTable1.getSelectedRowCount();
     int[] rowsselected = jTable1.getSelectedRows();
     int[] colsselected = jTable1.getSelectedColumns();
     if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0]
             && numrows == rowsselected.length)
         && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0]
             && numcols == colsselected.length))) {
       JOptionPane.showMessageDialog(
           null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
       return;
     }
     for (int i = 0; i < numrows; i++) {
       for (int j = 0; j < numcols; j++) {
         sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j]));
         if (j < numcols - 1) sbf.append("\t");
       }
       sbf.append("\n");
     }
     stsel = new StringSelection(sbf.toString());
     system = Toolkit.getDefaultToolkit().getSystemClipboard();
     system.setContents(stsel, stsel);
   }
   if (e.getActionCommand().compareTo("Paste") == 0) {
     System.out.println("Trying to Paste");
     int startRow = (jTable1.getSelectedRows())[0];
     int startCol = (jTable1.getSelectedColumns())[0];
     try {
       String trstring =
           (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor));
       System.out.println("String is:" + trstring);
       StringTokenizer st1 = new StringTokenizer(trstring, "\n");
       for (int i = 0; st1.hasMoreTokens(); i++) {
         rowstring = st1.nextToken();
         StringTokenizer st2 = new StringTokenizer(rowstring, "\t");
         for (int j = 0; st2.hasMoreTokens(); j++) {
           value = (String) st2.nextToken();
           if (startRow + i < jTable1.getRowCount() && startCol + j < jTable1.getColumnCount())
             jTable1.setValueAt(value, startRow + i, startCol + j);
           System.out.println(
               "Putting " + value + "at row = " + startRow + i + "column = " + startCol + j);
         }
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
Esempio n. 5
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;
    }
  }
Esempio n. 6
0
 public String getStringreprasentation() {
   StringBuffer sb = new StringBuffer();
   Vector<RowContainer> vec = getFilevector();
   for (RowContainer c : vec) {
     sb.append(c.getFile().getAbsolutePath()).append('\n');
   }
   return sb.toString();
 }
Esempio n. 7
0
  /** Returns the selected text, or null if no selection is active. */
  public final String getSelectedText() {
    if (selectionStart == selectionEnd) return null;

    if (rectSelect) {
      // Return each row of the selection on a new line

      Element map = document.getDefaultRootElement();

      int start = selectionStart - map.getElement(selectionStartLine).getStartOffset();
      int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

      // Certain rectangles satisfy this condition...
      if (end < start) {
        int tmp = end;
        end = start;
        start = tmp;
      }

      StringBuffer buf = new StringBuffer();
      Segment seg = new Segment();

      for (int i = selectionStartLine; i <= selectionEndLine; i++) {
        Element lineElement = map.getElement(i);
        int lineStart = lineElement.getStartOffset();
        int lineEnd = lineElement.getEndOffset() - 1;
        int lineLen = lineEnd - lineStart;

        lineStart = Math.min(lineStart + start, lineEnd);
        lineLen = Math.min(end - start, lineEnd - lineStart);

        getText(lineStart, lineLen, seg);
        buf.append(seg.array, seg.offset, seg.count);

        if (i != selectionEndLine) buf.append('\n');
      }

      return buf.toString();
    } else {
      return getText(selectionStart, selectionEnd - selectionStart);
    }
  }
Esempio n. 8
0
  /**
   * format a given Font to a string, following "Font.decode()" format, ie fontname-style-pointsize,
   * fontname-pointsize, fontname-style or fontname, where style is one of "BOLD", "ITALIC",
   * "BOLDITALIC" (default being PLAIN)
   */
  public static String formatFontAsProperties(Font font) {
    // jpicedt.Log.debug(new MiscUtilities(),"formatFontAsProperties","font="+font);
    String family = font.getFamily();
    /*
    System.out.println("family="+family);
    String faceName = font.getFontName();
    System.out.println("faceName="+faceName);
    String logicalName = font.getName();
    System.out.println("logicalName"+logicalName);
    String psName = font.getPSName();
    System.out.println("PSName="+psName);
    */

    StringBuffer buf = new StringBuffer(20);
    buf.append(family);
    buf.append("-");
    switch (font.getStyle()) {
      case Font.ITALIC:
        buf.append("ITALIC-");
        break;
      case Font.BOLD:
        buf.append("BOLD-");
        break;
      case Font.BOLD | Font.ITALIC:
        buf.append("BOLDITALIC-");
        break;
      default: // PLAIN -> nothing
    }
    buf.append(Integer.toString(font.getSize()));
    return buf.toString();
  }
  /** Import the given stream data into the text component. */
  protected void handleReaderImport(Reader in, JTextComponent c)
      throws BadLocationException, IOException {

    char[] buff = new char[1024];
    int nch;
    boolean lastWasCR = false;
    int last;
    StringBuffer sbuff = null;

    // Read in a block at a time, mapping \r\n to \n, as well as single
    // \r to \n.
    while ((nch = in.read(buff, 0, buff.length)) != -1) {

      if (sbuff == null) {
        sbuff = new StringBuffer(nch);
      }
      last = 0;

      for (int counter = 0; counter < nch; counter++) {

        switch (buff[counter]) {
          case '\r':
            if (lastWasCR) {
              if (counter == 0) sbuff.append('\n');
              else buff[counter - 1] = '\n';
            } else lastWasCR = true;
            break;
          case '\n':
            if (lastWasCR) {
              if (counter > (last + 1)) sbuff.append(buff, last, counter - last - 1);
              // else nothing to do, can skip \r, next write will
              // write \n
              lastWasCR = false;
              last = counter;
            }
            break;
          default:
            if (lastWasCR) {
              if (counter == 0) sbuff.append('\n');
              else buff[counter - 1] = '\n';
              lastWasCR = false;
            }
            break;
        } // End fo switch (buff[counter]).
      } // End of for (int counter = 0; counter < nch; counter++).

      if (last < nch) {
        if (lastWasCR) {
          if (last < (nch - 1)) sbuff.append(buff, last, nch - last - 1);
        } else sbuff.append(buff, last, nch - last);
      }
    } // End of while ((nch = in.read(buff, 0, buff.length)) != -1).

    if (withinSameComponent) {
      ((RTextArea) c).beginAtomicEdit();
    }

    if (lastWasCR) sbuff.append('\n');
    c.replaceSelection(sbuff != null ? sbuff.toString() : "");
  }
Esempio n. 10
0
  /** Places the selected text into the clipboard. */
  public void copy() {
    if (selectionStart != selectionEnd) {
      Clipboard clipboard = getToolkit().getSystemClipboard();

      String selection = getSelectedText();

      int repeatCount = inputHandler.getRepeatCount();
      StringBuffer buf = new StringBuffer();
      for (int i = 0; i < repeatCount; i++) buf.append(selection);

      clipboard.setContents(new StringSelection(buf.toString()), null);
    }
  }
  private String readLine(InputStream in) throws IOException {
    StringBuffer buf = new StringBuffer();

    while (true) {
      int i = in.read();

      if ((i == -1) || (i == '\n') || (i == '\r')) {
        return buf.toString();
      }

      buf.append((char) i);
    }

    // return new BufferedReader (new InputStreamReader (in)).readLine ();
  }
Esempio n. 12
0
  /** Inserts the clipboard contents into the text. */
  public void paste() {
    if (editable) {
      Clipboard clipboard = getToolkit().getSystemClipboard();
      try {
        // The MacOS MRJ doesn't convert \r to \n,
        // so do it here
        String selection =
            ((String) clipboard.getContents(this).getTransferData(DataFlavor.stringFlavor))
                .replace('\r', '\n');

        int repeatCount = inputHandler.getRepeatCount();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < repeatCount; i++) buf.append(selection);
        selection = buf.toString();
        setSelectedText(selection);
      } catch (Exception e) {
        getToolkit().beep();
        System.err.println("Clipboard does not" + " contain a string");
      }
    }
  }
Esempio n. 13
0
  private StringBuffer getDataFromReader(Reader br) {
    StringBuffer xferData = null;
    char[] buf = new char[513];
    int charsRead;

    try {
      do {
        charsRead = br.read(buf, 0, 512);
        if (charsRead != -1) {
          JConfig.log().logVerboseDebug("Read: " + charsRead + " characters.");
          if (xferData == null) {
            xferData = new StringBuffer();
          }
          xferData.append(buf, 0, charsRead);
        }
      } while (charsRead != -1);
      br.close();
    } catch (IOException e) {
      JConfig.log().logDebug("Caught an IO Exception trying to read the drag/drop data!");
      return null;
    }

    return xferData;
  }
  /**
   * Append <i>toPad</i> to the specified <i>appendTo</i>, as well as (<i>toPad.length () - len</i>)
   * spaces.
   *
   * @param toPad the {@link String} to pad
   * @param len the target length
   * @param appendTo the {@link StringBuffer} to which to append the padded {@link String}.
   */
  private final void pad(final String toPad, final int len, final StringBuffer appendTo) {
    appendTo.append(toPad);

    for (int i = 0; i < (len - toPad.length()); i++, appendTo.append(' ')) {;
    }
  }
Esempio n. 15
0
 private String fixLinuxString(String s) {
   StringBuffer sb = new StringBuffer(200);
   for (int i = 0; i < s.length(); i += 2) sb.append(s.charAt(i));
   return new String(sb);
 }