Example usage for javax.swing.text Element getElementIndex

List of usage examples for javax.swing.text Element getElementIndex

Introduction

In this page you can find the example usage for javax.swing.text Element getElementIndex.

Prototype

public int getElementIndex(int offset);

Source Link

Document

Gets the child element index closest to the given offset.

Usage

From source file:Main.java

private static final Element getLineElem(Document d, int offs) {
    Element map = d.getDefaultRootElement();
    int index = map.getElementIndex(offs);
    Element elem = map.getElement(index);
    if ((offs >= elem.getStartOffset()) && (offs < elem.getEndOffset())) {
        return elem;
    }//from www . j a  va2 s . com
    return null;
}

From source file:Main.java

protected static int getLineOfOffset(int offset, Document doc) throws BadLocationException {

    if (offset < 0 || doc == null) {
        throw new BadLocationException("", -1);
    } else if (offset > doc.getLength()) {
        throw new BadLocationException("", doc.getLength() + 1);
    } else {//from  w  ww . ja  va2s  . co m
        Element map = doc.getDefaultRootElement();
        return map.getElementIndex(offset);
    }
}

From source file:Main.java

private String addWhiteSpace(FilterBypass fb, int offset, String text) throws BadLocationException {
    Document doc = fb.getDocument();
    Element root = doc.getDefaultRootElement();
    int line = root.getElementIndex(offset);
    int i = root.getElement(line).getStartOffset();
    StringBuilder whiteSpace = new StringBuilder(text);

    while (true) {
        String temp = doc.getText(i, 1);
        if (temp.equals(" ") || temp.equals("\t")) {
            System.out.println("added");
            whiteSpace.append(temp);//from   w ww .j  a  v  a2 s. c  o m
            i++;
        } else {
            break;
        }
    }
    return whiteSpace.toString();
}

From source file:com.mirth.connect.client.ui.components.rsta.ac.js.MirthSourceCompletionProvider.java

@Override
public List<Completion> getCompletionsAt(JTextComponent tc, Point p) {
    Set<Completion> completions = new HashSet<Completion>();
    List<Completion> parentCompletions = super.getCompletionsAt(tc, p);
    if (CollectionUtils.isNotEmpty(parentCompletions)) {
        completions.addAll(parentCompletions);
    }//from  w  w w .  j av a  2s.  c  om

    int offset = tc.viewToModel(p);
    if (offset < 0 || offset >= tc.getDocument().getLength()) {
        lastCompletionsAtText = null;
        lastParameterizedCompletionsAt = null;
        return new ArrayList<Completion>(completions);
    }

    Segment s = new Segment();
    Document doc = tc.getDocument();
    Element root = doc.getDefaultRootElement();
    int line = root.getElementIndex(offset);
    Element elem = root.getElement(line);
    int start = elem.getStartOffset();
    int end = elem.getEndOffset() - 1;

    try {

        doc.getText(start, end - start, s);

        // Get the valid chars before the specified offset.
        int startOffs = s.offset + (offset - start) - 1;
        while (startOffs >= s.offset && Character.isLetterOrDigit(s.array[startOffs])) {
            startOffs--;
        }

        // Get the valid chars at and after the specified offset.
        int endOffs = s.offset + (offset - start);
        while (endOffs < s.offset + s.count && Character.isLetterOrDigit(s.array[endOffs])) {
            endOffs++;
        }

        int len = endOffs - startOffs - 1;
        if (len <= 0) {
            lastParameterizedCompletionsAt = null;
            return new ArrayList<Completion>(completions);
        }
        String text = new String(s.array, startOffs + 1, len);

        if (text.equals(lastCompletionsAtText)) {
            if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) {
                completions.addAll(lastParameterizedCompletionsAt);
            }
            return new ArrayList<Completion>(completions);
        }

        lastCompletionsAtText = text;
        lastParameterizedCompletionsAt = completionCache.getClassCompletions(tc, text);

        if (CollectionUtils.isNotEmpty(lastParameterizedCompletionsAt)) {
            completions.addAll(lastParameterizedCompletionsAt);
        }
        return new ArrayList<Completion>(completions);

    } catch (BadLocationException ble) {
        ble.printStackTrace(); // Never happens
    }

    lastCompletionsAtText = null;
    lastParameterizedCompletionsAt = null;

    return new ArrayList<Completion>(completions);
}

From source file:com.petersoft.advancedswing.enhancedtextarea.EnhancedTextArea.java

private void initGUI() {
    try {/*from ww  w .  ja  va  2s  . co  m*/
        BorderLayout thisLayout = new BorderLayout();
        this.setLayout(thisLayout);
        this.setPreferredSize(new java.awt.Dimension(725, 290));
        {
            jToolBar = new JToolBar();
            this.add(jToolBar, BorderLayout.NORTH);
            {
                jSaveButton = new JButton();
                jToolBar.add(jSaveButton);
                jSaveButton.setText("Save");
                jSaveButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/disk.png")));
                jSaveButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jSaveButtonActionPerformed(evt);
                    }
                });
            }
            {
                jLineWrapButton = new JToggleButton();
                jToolBar.add(jLineWrapButton);
                jLineWrapButton.setText("Wrap");
                jLineWrapButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/linewrap.png")));
                jLineWrapButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jLineWrapButtonActionPerformed(evt);
                    }
                });
            }
            {
                jFontBiggerButton = new JButton();
                jToolBar.add(jFontBiggerButton);
                jFontBiggerButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/font_add.png")));
                jFontBiggerButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jFontBiggerButtonActionPerformed(evt);
                    }
                });
            }
            {
                jFontSmallerButton = new JButton();
                jToolBar.add(jFontSmallerButton);
                jFontSmallerButton.setIcon(new ImageIcon(getClass().getClassLoader()
                        .getResource("com/petersoft/advancedswing/enhancedtextarea/font_delete.png")));
                jFontSmallerButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jFontSmallerButtonActionPerformed(evt);
                    }
                });
            }
            {
                jLabel1 = new JLabel();
                jToolBar.add(jLabel1);
                jLabel1.setText(" ");
            }
            {
                jSearchTextField = new JSearchTextField();
                jToolBar.add(jSearchTextField);
                jSearchTextField.setMaximumSize(new java.awt.Dimension(100, 22));
                jSearchTextField.setPreferredSize(new java.awt.Dimension(100, 22));
                jSearchTextField.setSize(new java.awt.Dimension(100, 22));
                jSearchTextField.addKeyListener(new KeyAdapter() {
                    public void keyReleased(KeyEvent evt) {
                        jSearchTextFieldKeyReleased(evt);
                    }
                });

            }
            {
                jSeparatorLabel = new JLabel();
                jToolBar.add(jSeparatorLabel);
                jSeparatorLabel.setText(" ");
            }
            {
                GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
                Font[] fonts = e.getAllFonts();
                String fontNames[] = new String[fonts.length];
                int x = 0;
                for (Font f : fonts) {
                    fontNames[x++] = f.getFontName();
                }
                ComboBoxModel jFontComboBoxModel = new DefaultComboBoxModel(fontNames);
                jFontComboBox = new JComboBox();
                jToolBar.add(jFontComboBox);
                jFontComboBox.setModel(jFontComboBoxModel);
                jFontComboBox.setMaximumSize(new java.awt.Dimension(180, 22));
                jFontComboBox.setPreferredSize(new java.awt.Dimension(180, 22));
                jFontComboBox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jFontComboBoxActionPerformed(evt);
                    }
                });
            }
            {
                pager = new Pager();
                jToolBar.add(pager);
                pager.setVisible(false);
            }
        }
        {
            jScrollPane1 = new JScrollPane();
            this.add(jScrollPane1, BorderLayout.CENTER);
            {
                jTextArea = new JTextArea();
                jTextArea.getDocument().addDocumentListener(this);
                lines = new JTextArea(" 1 ");
                lines.setBackground(new Color(200, 230, 245));
                lines.setEditable(false);
                jScrollPane1.setRowHeaderView(lines);

                jTextArea.getDocument().addDocumentListener(new DocumentListener() {
                    public String getText() {
                        int caretPosition = jTextArea.getDocument().getLength();
                        Element root = jTextArea.getDocument().getDefaultRootElement();

                        int base = 0;
                        if (separateByLine == false) {
                            if (str != null) {
                                base = StringUtils.countMatches(
                                        str.substring(0, (pager.getPage() - 1) * pageSize),
                                        System.getProperty("line.separator"));
                                if (base == 1) {
                                    base = 0;
                                }
                            }
                        } else {
                            base = (pager.getPage() - 1) * pageSize;
                        }
                        base += lineNoBase;
                        String text = " " + (base + 1) + " " + System.getProperty("line.separator");
                        for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
                            text += " " + (base + i) + " " + System.getProperty("line.separator");
                        }
                        return text;
                    }

                    @Override
                    public void changedUpdate(DocumentEvent de) {
                        lines.setText(getText());
                    }

                    @Override
                    public void insertUpdate(DocumentEvent de) {
                        lines.setText(getText());
                    }

                    @Override
                    public void removeUpdate(DocumentEvent de) {
                        lines.setText(getText());
                    }

                });
                jScrollPane1.setViewportView(jTextArea);
            }
        }
        {
            jStatusPanel = new JPanel();
            FlowLayout jStatusPanelLayout = new FlowLayout();
            jStatusPanelLayout.setAlignment(FlowLayout.LEFT);
            jStatusPanel.setLayout(jStatusPanelLayout);
            this.add(jStatusPanel, BorderLayout.SOUTH);
            {
                jStatusLabel = new JLabel();
                jStatusPanel.add(jStatusLabel);
            }
            {
                jSearchLabel = new JLabel();
                jStatusPanel.add(jSearchLabel);
            }
        }
        this.jFontComboBox.setSelectedItem(jTextArea.getFont().getFamily() + ".plain");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Returns the line number of the given character offset, for the current document.
 *
 * @param offset Character offset./*from  w  w w  . j  a  va  2 s .  c o  m*/
 * @return Line number.
 * @throws BadLocationException
 */
public int getLineOfOffset(int offset) throws BadLocationException {
    if (offset < 0) {
        throw new BadLocationException("Can't translate offset to line", -1);
    } else if (offset > doc.getLength()) {
        throw new BadLocationException("Can't translate offset to line", doc.getLength() + 1);
    } else {
        Element map = doc.getDefaultRootElement();
        return map.getElementIndex(offset);
    }
}

From source file:org.domainmath.gui.MainFrame.java

public void gotoLine(String goto_file, int lineRequested) {
    if (fileTab.getSelectedIndex() >= 0) {
        int indexOf = MainFrame.fileNameList.indexOf(goto_file);
        RTextScrollPane t = (RTextScrollPane) fileTab.getComponentAt(indexOf);
        RSyntaxTextArea selectedArea = (RSyntaxTextArea) t.getTextArea();
        try {/*w  w  w. j  a  va  2s.c om*/
            Element element = selectedArea.getDocument().getDefaultRootElement();

            int rowCount = element.getElementCount();
            if (lineRequested > rowCount || lineRequested < 0) {

                setVisible(false);
                return;
            }
            Element row = null;
            int firstCharacter = 0;
            int rowNumber = 0;
            for (int i = 0; i < lineRequested; ++i) {
                firstCharacter = getFirstCharacter(row);
                rowNumber = element.getElementIndex(firstCharacter);
                row = element.getElement(rowNumber);
            }
            int lastColumnInRow = row.getEndOffset();
            selectedArea.select(firstCharacter, lastColumnInRow - 1);

        } catch (Exception e) {

        }
    }
}

From source file:org.domainmath.gui.MainFrame.java

private void gotoItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gotoItemActionPerformed
    if (fileTab.getSelectedIndex() >= 0) {
        String s = JOptionPane.showInputDialog("Line Number:");
        RTextScrollPane t = (RTextScrollPane) fileTab.getComponentAt(fileTab.getSelectedIndex());
        RSyntaxTextArea selectedArea = (RSyntaxTextArea) t.getTextArea();
        try {/* w ww .j a va2  s .c  om*/
            Element element = selectedArea.getDocument().getDefaultRootElement();
            int lineRequested = Integer.parseInt(s);
            int rowCount = element.getElementCount();
            if (lineRequested > rowCount || lineRequested < 0) {

                setVisible(false);
                return;
            }
            Element row = null;
            int firstCharacter = 0;
            int rowNumber = 0;
            for (int i = 0; i < lineRequested; ++i) {
                firstCharacter = getFirstCharacter(row);
                rowNumber = element.getElementIndex(firstCharacter);
                row = element.getElement(rowNumber);
            }
            int lastColumnInRow = row.getEndOffset();
            selectedArea.select(firstCharacter, lastColumnInRow - 1);

        } catch (Exception e) {

        }
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

/**
 * Returns the row number at the specified position.
 *
 * @param position - the position/*  www .  j  a  v a 2 s. c o  m*/
 */
protected int getRowAt(int position) {
    Element map = getElementMap();
    return map.getElementIndex(position);
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

/**
 * Called when the caret position is updated.
 *
 * @param e the caret event/*www  . ja v a  2s  .c  o  m*/
 */
public void caretUpdate(CaretEvent ce) {

    super.caretUpdate(ce);
    currentPosition = getCaretPosition();

    Element map = getElementMap();
    int row = map.getElementIndex(currentPosition);

    if (currentRow != row) {
        currentRow = row;
        //lineBorder.setRowCount(map.getElementCount());
    }

    Element lineElem = map.getElement(row);
    int col = currentPosition - lineElem.getStartOffset();
    editorPanel.getStatusBar().setCaretPosition(row + 1, col + 1);

    repaint();
}