Ejemplo n.º 1
2
  @Override
  protected Transferable createTransferable(JComponent c) {
    JTextPane aTextPane = (JTextPane) c;

    HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit());
    StyledDocument sdoc = aTextPane.getStyledDocument();
    int sel_start = aTextPane.getSelectionStart();
    int sel_end = aTextPane.getSelectionEnd();

    int i = sel_start;
    StringBuilder output = new StringBuilder();
    while (i < sel_end) {
      Element e = sdoc.getCharacterElement(i);
      Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute);
      int start = e.getStartOffset(), end = e.getEndOffset();
      if (nameAttr == HTML.Tag.BR) {
        output.append("\n");
      } else if (nameAttr == HTML.Tag.CONTENT) {
        if (start < sel_start) {
          start = sel_start;
        }
        if (end > sel_end) {
          end = sel_end;
        }
        try {
          String str = sdoc.getText(start, end - start);
          output.append(str);
        } catch (BadLocationException ble) {
          Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage());
        }
      }
      i = end;
    }
    return new StringSelection(output.toString());
  }
Ejemplo n.º 2
0
  private void _applyFontStyleForSelection(Font font) {
    StyledDocument doc = mTextEditor.getStyledDocument();
    MutableAttributeSet attrs = mTextEditor.getInputAttributes();
    StyleConstants.setFontFamily(attrs, font.getFamily());
    StyleConstants.setFontSize(attrs, font.getSize());
    StyleConstants.setBold(attrs, ((font.getStyle() & Font.BOLD) != 0));
    StyleConstants.setItalic(attrs, ((font.getStyle() & Font.ITALIC) != 0));
    StyleConstants.setUnderline(attrs, ((font.getStyle() & Font.CENTER_BASELINE) != 0));

    int start = mTextEditor.getSelectionStart();
    int end = mTextEditor.getSelectionEnd();
    doc.setCharacterAttributes(start, (end - start), attrs, false);
  }
Ejemplo n.º 3
0
  /** Creates the text area. */
  private void initTextArea() {
    textArea.setOpaque(false);
    textArea.setEditable(false);
    StyledDocument doc = textArea.getStyledDocument();

    MutableAttributeSet standard = new SimpleAttributeSet();
    StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
    StyleConstants.setFontFamily(standard, textArea.getFont().getFamily());
    StyleConstants.setFontSize(standard, 12);
    doc.setParagraphAttributes(0, 0, standard, true);

    parentWindow.addSearchFieldListener(this);
  }
Ejemplo n.º 4
0
 void editorPane_keyPressed(KeyEvent e) {
   StyledDocument doc = editorPane.getStyledDocument();
   int pos = editorPane.getCaretPosition();
   int code = e.getKeyCode();
   Element el;
   switch (code) {
     case KeyEvent.VK_BACK_SPACE:
     case KeyEvent.VK_DELETE:
     case KeyEvent.VK_LEFT:
     case KeyEvent.VK_KP_LEFT:
       if (pos == 0) return;
       // we want to get the element to the left of position.
       el = doc.getCharacterElement(pos - 1);
       break;
     case KeyEvent.VK_RIGHT:
     case KeyEvent.VK_KP_RIGHT:
       // we want to get the element to the right of position.
       el = doc.getCharacterElement(pos + 1);
       break;
     default:
       return; // bail we don't handle it.
   }
   AttributeSet attr = el.getAttributes();
   String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute);
   int el_range = el.getEndOffset() - el.getStartOffset() - 1;
   if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) {
     try {
       switch (code) {
         case KeyEvent.VK_BACK_SPACE:
         case KeyEvent.VK_DELETE:
           doc.remove(el.getStartOffset(), el_range);
           break;
         case KeyEvent.VK_LEFT:
         case KeyEvent.VK_KP_LEFT:
           editorPane.setCaretPosition(pos - el_range);
           break;
         case KeyEvent.VK_RIGHT:
         case KeyEvent.VK_KP_RIGHT:
           editorPane.setCaretPosition(pos + (el_range));
           break;
       }
     } catch (BadLocationException ex) {
     }
   }
 }
Ejemplo n.º 5
0
  // Update the box that shows current actions.
  public void updateGUI(String message) {
    StyledDocument text = updateBox.getStyledDocument();
    SimpleAttributeSet currentWords = new SimpleAttributeSet();
    StyleConstants.setBold(currentWords, true);
    SimpleAttributeSet pastWords = new SimpleAttributeSet();
    StyleConstants.setBold(pastWords, false);

    try {
      text.setCharacterAttributes(0, text.getLength(), pastWords, true);
      text.insertString(0, message + "\n", currentWords);
    } catch (BadLocationException e) {
      // TODO Auto-generated catch block
      System.err.println("Bad location exception while styling updateBox.");
      e.printStackTrace();
    }

    updateBox.setCaretPosition(0);
  }
Ejemplo n.º 6
0
  /**
   * Sets the reason of a call failure if one occurs. The renderer should display this reason to the
   * user.
   *
   * @param reason the reason to display
   */
  public void setErrorReason(final String reason) {
    if (!SwingUtilities.isEventDispatchThread()) {
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              setErrorReason(reason);
            }
          });
      return;
    }

    if (errorMessageComponent == null) {
      errorMessageComponent = new JTextPane();

      JTextPane textPane = (JTextPane) errorMessageComponent;
      textPane.setEditable(false);
      textPane.setOpaque(false);

      StyledDocument doc = textPane.getStyledDocument();

      MutableAttributeSet standard = new SimpleAttributeSet();
      StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
      StyleConstants.setFontFamily(standard, textPane.getFont().getFamily());
      StyleConstants.setFontSize(standard, 12);
      doc.setParagraphAttributes(0, 0, standard, true);

      GridBagConstraints constraints = new GridBagConstraints();
      constraints.fill = GridBagConstraints.HORIZONTAL;
      constraints.gridx = 0;
      constraints.gridy = 4;
      constraints.weightx = 1;
      constraints.weighty = 0;
      constraints.insets = new Insets(5, 0, 0, 0);

      add(errorMessageComponent, constraints);
      this.revalidate();
    }

    errorMessageComponent.setText(reason);

    if (isVisible()) errorMessageComponent.repaint();
  }
Ejemplo n.º 7
0
  protected void buildErrorPanel() {
    errorPanel = new JPanel();
    GroupLayout layout = new GroupLayout(errorPanel);
    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);
    errorPanel.setLayout(layout);
    //    errorPanel.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK));
    errorMessage = new JTextPane();
    errorMessage.setEditable(false);
    errorMessage.setContentType("text/html");
    errorMessage.setText(
        "<html><body>Could not connect to the Processing server.<br>"
            + "Contributions cannot be installed or updated without an Internet connection.<br>"
            + "Please verify your network connection again, then try connecting again.</body></html>");
    errorMessage.setFont(Toolkit.getSansFont(14, Font.PLAIN));
    errorMessage.setMaximumSize(new Dimension(550, 50));
    errorMessage.setOpaque(false);

    StyledDocument doc = errorMessage.getStyledDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(0, doc.getLength(), center, false);

    closeButton = new JButton("X");
    closeButton.setContentAreaFilled(false);
    closeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            contribDialog.makeAndShowTab(false, false);
          }
        });
    tryAgainButton = new JButton("Try Again");
    tryAgainButton.setFont(Toolkit.getSansFont(14, Font.PLAIN));
    tryAgainButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            contribDialog.makeAndShowTab(false, true);
            contribDialog.downloadAndUpdateContributionListing(editor.getBase());
          }
        });
    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(errorMessage)
                    .addComponent(
                        tryAgainButton,
                        StatusPanel.BUTTON_WIDTH,
                        StatusPanel.BUTTON_WIDTH,
                        StatusPanel.BUTTON_WIDTH))
            .addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
            .addComponent(closeButton));
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout.createParallelGroup().addComponent(errorMessage).addComponent(closeButton))
            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(tryAgainButton));
    errorPanel.setBackground(Color.PINK);
    errorPanel.validate();
  }
Ejemplo n.º 8
0
  public static void main() {
    // Main
    frame = new JFrame("Java Playground");
    frame.setSize(640, 480);
    // Make sure the divider is properly resized
    frame.addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent c) {
            splitter.setDividerLocation(.8);
          }
        });
    // Make sure the JVM is reset on close
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosed(WindowEvent w) {
            new FrameAction().kill();
          }
        });

    // Setting up the keybinding
    // Ctrl+k or Cmd+k -> compile
    bind(KeyEvent.VK_K);

    // Ctrl+e or Cmd+e -> console
    bind(KeyEvent.VK_E);

    // Save, New file, Open file, Print.
    // Currently UNUSED until I figure out how normal java files and playground files will
    // interface.
    bind(KeyEvent.VK_S);
    bind(KeyEvent.VK_N);
    bind(KeyEvent.VK_O);
    bind(KeyEvent.VK_P);

    // Binds the keys to the action defined in the FrameAction class.
    frame.getRootPane().getActionMap().put("console", new FrameAction());

    // The main panel for typing code in.
    text = new JTextPane();
    textScroll = new JScrollPane(text);
    textScroll.setBorder(null);
    textScroll.setPreferredSize(new Dimension(640, 480));

    // Document with syntax highlighting. Currently unfinished.
    doc = text.getStyledDocument();
    doc.addDocumentListener(
        new DocumentListener() {
          public void changedUpdate(DocumentEvent d) {}

          public void insertUpdate(DocumentEvent d) {}

          public void removeUpdate(DocumentEvent d) {}
        });

    ((AbstractDocument) doc).setDocumentFilter(new NewLineFilter());

    // The output log; a combination compiler warning/error/runtime error/output log.
    outputText = new JTextPane();
    outputScroll = new JScrollPane(outputText);
    outputScroll.setBorder(null);

    // "Constant" for the error font
    error = new SimpleAttributeSet();
    error.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
    error.addAttribute(StyleConstants.Foreground, Color.RED);

    // "Constant" for the warning message font
    warning = new SimpleAttributeSet();
    warning.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
    warning.addAttribute(StyleConstants.Foreground, Color.PINK);

    // "Constant" for the debugger error font
    progErr = new SimpleAttributeSet();
    progErr.addAttribute(StyleConstants.Foreground, Color.BLUE);

    // Print streams to redirect System.out and System.err.
    out = new TextOutputStream(outputText, null);
    err = new TextOutputStream(outputText, error);
    System.setOut(new PrintStream(out));
    System.setErr(new PrintStream(err));

    // Sets up the output log
    outputText.setEditable(false);
    outputScroll.setVisible(true);

    // File input/output setup
    chooser = new JFileChooser();

    // Setting up miscellaneous stuff
    compiler = ToolProvider.getSystemJavaCompiler();
    JVMrunning = false;
    redirectErr = null;
    redirectOut = null;
    redirectIn = null;

    // Sets up the splitter pane and opens the program up
    splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, textScroll, outputScroll);
    consoleDisplayed = false;
    splitter.remove(outputScroll); // Initially hides terminal until it is needed
    splitter.setOneTouchExpandable(true);
    frame.add(splitter);
    frame.setVisible(true);

    // Sets the divider to the proper one, for debugging
    // splitter.setDividerLocation(.8);
  }
Ejemplo n.º 9
0
    @Override
    public void actionPerformed(ActionEvent e) {

      licence_text =
          new String(
              "This program is free software: you can redistribute it and/or modify\n"
                  + "it under the terms of the GNU General Public License as published by\n"
                  + "the Free Software Foundation, either version 3 of the License, or\n"
                  + "(at your option) any later version.\n"
                  + "\n"
                  + "This program is distributed in the hope that it will be useful,\n"
                  + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
                  + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
                  + "GNU General Public License for more details.\n"
                  + "\n"
                  + "You should have received a copy of the GNU General Public License\n"
                  + "along with this program.  If not, see <http://www.gnu.org/licenses/>.\n"
                  + "\n\n\n");

      try {
        InputStream ips = new FileInputStream(getClass().getResource("COPYING").getPath());
        InputStreamReader ipsr = new InputStreamReader(ips);
        BufferedReader br = new BufferedReader(ipsr);

        String line;
        while ((line = br.readLine()) != null) {
          licence_text += line + '\n';
        }
        br.close();
      } catch (Exception e1) {
      }

      Dimension dimension = new Dimension(600, 400);

      JDialog licence = new JDialog(memento, "Licence");

      JTextPane text_pane = new JTextPane();
      text_pane.setEditable(false);
      text_pane.setPreferredSize(dimension);
      text_pane.setSize(dimension);

      StyledDocument doc = text_pane.getStyledDocument();

      Style justified =
          doc.addStyle(
              "justified",
              StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
      StyleConstants.setAlignment(justified, StyleConstants.ALIGN_JUSTIFIED);

      try {
        doc.insertString(0, licence_text, justified);
      } catch (BadLocationException ble) {
        System.err.println("Couldn't insert initial text into text pane.");
      }
      Style logicalStyle = doc.getLogicalStyle(0);
      doc.setParagraphAttributes(0, licence_text.length(), justified, false);
      doc.setLogicalStyle(0, logicalStyle);

      JScrollPane paneScrollPane = new JScrollPane(text_pane);
      paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      paneScrollPane.setPreferredSize(dimension);
      paneScrollPane.setMinimumSize(dimension);

      JPanel pan = new JPanel();
      LayoutManager layout = new BorderLayout();
      pan.setLayout(layout);

      pan.add(new JScrollPane(paneScrollPane), BorderLayout.CENTER);
      JButton close = new JButton("Fermer");
      close.addActionListener(new ButtonCloseActionListener(licence));
      JPanel button_panel = new JPanel();
      FlowLayout button_panel_layout = new FlowLayout(FlowLayout.RIGHT, 20, 20);
      button_panel.setLayout(button_panel_layout);

      button_panel.add(close);
      pan.add(button_panel, BorderLayout.SOUTH);

      licence.add(pan);

      licence.pack();
      licence.setLocationRelativeTo(memento);
      licence.setVisible(true);
    }