Java Code Examples for javax.swing.JTextArea.getCaret()

The following are Jave code examples for showing how to use getCaret() of the javax.swing.JTextArea class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: java-course   File: LowerCaseAction.java   Source Code and License Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret position = currentEditor.getCaret();

    int len = Math.abs(currentEditor.getCaret().getDot()
            - currentEditor.getCaret().getMark());
    int offset = Math.min(currentEditor.getCaret().getDot(), currentEditor
            .getCaret().getMark());

    try {
        String text = document.getText(offset, len);
        text = lowerCase(text);
        document.remove(offset, len);
        document.insertString(offset, text, null);
        // Reselect text
        position.setDot(offset);
        position.moveDot(offset + len);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }
}
 
Example 2
Project: java-course   File: UpperCaseAction.java   Source Code and License Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret position = currentEditor.getCaret();

    int len = Math.abs(currentEditor.getCaret().getDot()
            - currentEditor.getCaret().getMark());
    int offset = Math.min(currentEditor.getCaret().getDot(), currentEditor
            .getCaret().getMark());

    try {
        String text = document.getText(offset, len);
        text = upperCase(text);
        document.remove(offset, len);
        document.insertString(offset, text, null);
        position.setDot(offset);
        position.moveDot(offset + len);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }
}
 
Example 3
Project: incubator-netbeans   File: CslTestBase.java   Source Code and License Vote up 5 votes
protected void assertAutoQuery(QueryType queryType, String source, String typedText) {
    CodeCompletionHandler completer = getCodeCompleter();
    int caretPos = source.indexOf('^');
    source = source.substring(0, caretPos) + source.substring(caretPos+1);

    BaseDocument doc = getDocument(source);
    JTextArea ta = new JTextArea(doc);
    Caret caret = ta.getCaret();
    caret.setDot(caretPos);

    QueryType qt = completer.getAutoQuery(ta, typedText);
    assertEquals(queryType, qt);
}
 
Example 4
Project: PTEAssistant   File: Console.java   Source Code and License Vote up 5 votes
public Console() {
    setLayout(new BorderLayout());
    setBorder(new TitledBorder("控制台"));
    textarea = new JTextArea();
    textarea.setCaretPosition(textarea.getText().length());
    textarea.setFont(new Font("新宋体", Font.PLAIN, 12));
    add(textarea);
    DefaultCaret caret = (DefaultCaret) textarea.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    scrollPane = new JScrollPane();
    scrollPane.setViewportView(textarea);
    add(scrollPane, BorderLayout.CENTER);
    
    welcome();
}
 
Example 5
Project: java-course   File: SortLinesDescendingAction.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret caret = currentEditor.getCaret();

    int startCaret = Math.min(caret.getDot(), caret.getMark());
    int endCaret = Math.max(caret.getDot(), caret.getMark());

    try {

        int startLine = currentEditor.getLineOfOffset(startCaret);
        int endLine = currentEditor.getLineOfOffset(endCaret);
        int fromPos = currentEditor.getLineStartOffset(startLine);
        int length = currentEditor.getLineEndOffset(endLine) - fromPos;

        String text = currentEditor.getText(fromPos, length);
        text = sortLinesDesc(text);
        document.remove(fromPos, length);
        document.insertString(fromPos, text, null);
        caret.setDot(fromPos);
        caret.moveDot(fromPos + length);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }

}
 
Example 6
Project: java-course   File: SortLinesAscendingAction.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret caret = currentEditor.getCaret();

    int startCaret = Math.min(caret.getDot(), caret.getMark());
    int endCaret = Math.max(caret.getDot(), caret.getMark());

    try {

        int startLine = currentEditor.getLineOfOffset(startCaret);
        int endLine = currentEditor.getLineOfOffset(endCaret);
        int fromPos = currentEditor.getLineStartOffset(startLine);
        int length = currentEditor.getLineEndOffset(endLine) - fromPos;

        String text = currentEditor.getText(fromPos, length);
        text = sortLinesAsc(text);
        document.remove(fromPos, length);
        document.insertString(fromPos, text, null);
        caret.setDot(fromPos);
        caret.moveDot(fromPos + length);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }

}
 
Example 7
Project: java-course   File: UniqueLinesAction.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(ActionEvent e) {
    JTextArea currentEditor = observer.getActiveEditor().getEditor();
    Document document = currentEditor.getDocument();
    Caret caret = currentEditor.getCaret();

    int startCaret = Math.min(caret.getDot(), caret.getMark());
    int endCaret = Math.max(caret.getDot(), caret.getMark());

    try {

        int startLine = currentEditor.getLineOfOffset(startCaret);
        int endLine = currentEditor.getLineOfOffset(endCaret);
        int fromPos = currentEditor.getLineStartOffset(startLine);
        int length = currentEditor.getLineEndOffset(endLine) - fromPos + 1;

        String text = currentEditor.getText(fromPos, length);
        text = removeLines(text);
        document.remove(fromPos, length - 1);
        document.insertString(fromPos, text, null);
        caret.setDot(fromPos);
        caret.moveDot(length - 1);
        currentEditor.requestFocus();
    } catch (BadLocationException e1) {
        observer.errorMessage(e1);
    }
}
 
Example 8
Project: thornsec-core   File: TextAreaOutputStream.java   Source Code and License Vote up 4 votes
public TextAreaOutputStream(JTextArea area) {
	this.area = area;
	DefaultCaret caret = (DefaultCaret)area.getCaret();
	caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
 
Example 9
Project: Panako   File: SyncSinkFrame.java   Source Code and License Vote up 4 votes
public SyncSinkFrame(){
	super("SyncSink");
	
	logTextField = new JTextArea();
	logTextField.setEditable(false);
	DefaultCaret caret = (DefaultCaret)logTextField.getCaret();
	caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
	
	StringBuilder sb = new StringBuilder();
	sb.append("----------------------------------------\n");
	sb.append("Configuration currently in use: \n");
	for(Key key : Key.values()){
		sb.append("\t");
		sb.append(key.name());
		sb.append("=");
		sb.append(Config.get(key));
		sb.append("\n");
	}
	sb.append("----------------------------------------\n");
	logTextField.setText(sb.toString());
	
	
	this.setLayout(new BorderLayout());
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
	cs = new CoordinateSystem(AxisUnit.OCCURENCES, 0, 1000);
	
	linkedPanel = new LinkedPanel(cs);
	linkedPanel.addLayer(new BackgroundLayer(cs));
	linkedPanel.addLayer(new ZoomMouseListenerLayer());
	linkedPanel.addLayer(new DragMouseListenerLayer(cs));
	linkedPanel.addLayer(new BackgroundLayer(cs));
	linkedPanel.addLayer(new TimeAxisLayer(cs));
	linkedPanel.addLayer(new SelectionLayer(cs));
	linkedPanel.getViewPort().addViewPortChangedListener(this);
	
	matches = new ArrayList<NFFTSyncMatch>();
	
	this.streamLayers = new ArrayList<StreamLayer>();
	this.streamFiles = new ArrayList<File>();
	
	JTabbedPane tabbedPane = new JTabbedPane();

	
	tabbedPane.addTab("Timebox plot", null, linkedPanel,"Timebox plots");
	tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);

	
	tabbedPane.addTab("Messages", null, new JScrollPane(logTextField),"Logs messages");
	tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
	
	tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
	tabbedPane.setBorder(new EmptyBorder(0,0,0,0));
	
	this.add(tabbedPane,BorderLayout.CENTER);
	this.add(createStatusBarPanel(),BorderLayout.SOUTH);
	
	new FileDrop(null, tabbedPane, /*dragBorder,*/ new FileDrop.Listener(){   
		public void filesDropped( final File[] files ){  
			new Thread(new Runnable(){
				@Override
				public void run() {
					for( int i = 0; i < files.length; i++) {   
						final File fileToAdd = files[i];
						logMessage("Adding " + fileToAdd.getPath()  + "...");							
			            openFile(fileToAdd,streamFiles.size());
			            logMessage("Added " + fileToAdd.getPath()  + ".");	
	                }
			}},"File adding thread").start();
		}
       });
}
 
Example 10
Project: powertext   File: SearchEngine.java   Source Code and License Vote up 4 votes
/**
 * Finds the next instance of the string/regular expression specified
 * from the caret position.  If a match is found, it is selected in this
 * text area.
 *
 * @param textArea The text area in which to search.
 * @param context What to search for and all search options.
 * @return The result of the operation.
 * @throws PatternSyntaxException If this is a regular expression search
 *         but the search text is an invalid regular expression.
 * @see #replace(RTextArea, SearchContext)
 * @see #replaceAll(RTextArea, SearchContext)
 */
public static SearchResult find(JTextArea textArea, SearchContext context) {

	// Always clear previous "mark all" highlights
	if (textArea instanceof RTextArea || context.getMarkAll()) {
		((RTextArea)textArea).clearMarkAllHighlights();
	}
	boolean doMarkAll = textArea instanceof RTextArea && context.getMarkAll();

	String text = context.getSearchFor();
	if (text==null || text.length()==0) {
		if (doMarkAll) {
			// Force "mark all" event to be broadcast so listeners know to
			// clear their mark-all markers.  The RSTA already cleared its
			// highlights above, but cleraMarkAllHighlights() doesn't fire
			// an event itself for performance reasons.
			List<DocumentRange> emptyRangeList = Collections.emptyList();
			((RTextArea)textArea).markAll(emptyRangeList);
		}
		return new SearchResult();
	}

	// Be smart about what position we're "starting" at.  We don't want
	// to find a match in the currently selected text (if any), so we
	// start searching AFTER the selection if searching forward, and
	// BEFORE the selection if searching backward.
	Caret c = textArea.getCaret();
	boolean forward = context.getSearchForward();
	int start = forward ? Math.max(c.getDot(), c.getMark()) :
					Math.min(c.getDot(), c.getMark());

	String findIn = getFindInText(textArea, start, forward);
	if (findIn==null || findIn.length()==0) {
		return new SearchResult();
	}

	int markAllCount = 0;
	if (doMarkAll) {
		markAllCount = markAllImpl((RTextArea)textArea, context).
				getMarkedCount();
	}

	SearchResult result = SearchEngine.findImpl(findIn, context);
	if (result.wasFound() && !result.getMatchRange().isZeroLength()) {
		// Without this, if JTextArea isn't in focus, selection
		// won't appear selected.
		textArea.getCaret().setSelectionVisible(true);
		if (forward && start>-1) {
			result.getMatchRange().translate(start);
		}
		RSyntaxUtilities.selectAndPossiblyCenter(textArea,
				result.getMatchRange(), true);
	}

	result.setMarkedCount(markAllCount);
	return result;

}
 
Example 11
Project: powertext   File: SearchEngine.java   Source Code and License Vote up 3 votes
/**
 * Makes the caret's dot and mark the same location so that, for the
 * next search in the specified direction, a match will be found even
 * if it was within the original dot and mark's selection.
 *
 * @param textArea The text area.
 * @param forward Whether the search will be forward through the
 *        document (<code>false</code> means backward).
 * @return The new dot and mark position.
 */
private static int makeMarkAndDotEqual(JTextArea textArea,
									boolean forward) {
	Caret c = textArea.getCaret();
	int val = forward ? Math.min(c.getDot(), c.getMark()) :
					Math.max(c.getDot(), c.getMark());
	c.setDot(val);
	return val;
}