Selecting Text in a JTextArea

Hi, I have this problem with the JTextArea Caret positioning behaviour.
I wanna select some text when I click (click, no dragging included) on a line. I use setcaretposition in the beggining of the line and movecaretposition in the end of the line.
Nothing happens!!
If I click the mouse and drag it a little bit then it works fine selecting the text showing the right colors and everything.
I tried with the addhighlight method in the higlighter instance of JTextArea but it doesn't really select it, just changes it color.
What do I have to do so that I can select text without having to drag when I click??
Thaks a lot

This shows you how to do it using a right click:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class TextAreaTest extends JFrame
     JTextArea textArea;
     JScrollPane scrollPane;
     public TextAreaTest()
          textArea = new JTextArea( "one two\nthree four", 10, 30 )
               //  the tab character is not inserted into the text area
               public boolean isManagingFocus()
                    return false;
          textArea.setLineWrap( true );
          textArea.setSize( textArea.getPreferredSize() );
          textArea.setSelectionColor( Color.red );
          textArea.setSelectedTextColor( Color.green );
          try
               System.out.println( textArea.modelToView( 4 ) );
               System.out.println( Utilities.getRowStart(textArea, 4) );
          catch (Exception e) {}
          textArea.addMouseListener( new MouseAdapter()
               public void mouseClicked(MouseEvent e)
                    if ( SwingUtilities.isRightMouseButton(e) )
                         try
                              int offset = textArea.viewToModel( e.getPoint() );
                              System.out.println( textArea.modelToView( offset ) );
                              int start = Utilities.getWordStart(textArea, offset);
                              int end = Utilities.getWordEnd(textArea, offset);
                              String word = textArea.getDocument().getText(start, end-start);
                              System.out.println( "Selected word: " + word );
                              int rowStart = Utilities.getRowStart(textArea, offset);
                              int rowEnd = Utilities.getRowEnd(textArea, offset);
                              System.out.println( "Row start offset: " + rowStart );
                              System.out.println( "Row end   offset: " + rowEnd );
                              textArea.select(rowStart, rowEnd);
                         catch (Exception e2) {}
          textArea.addCaretListener( new CaretListener()
               public void caretUpdate(CaretEvent e)
                    int caretPosition = textArea.getCaretPosition();
                    Element root = textArea.getDocument().getDefaultRootElement();
                    int row = root.getElementIndex( caretPosition );
                    int column = caretPosition - root.getElement( row ).getStartOffset();
                    System.out.println( "Row   : " + ( row + 1 ) );
                    System.out.println( "Column: " + ( column + 1 ) );
          textArea.addKeyListener( new KeyAdapter()
               public void keyPressed(KeyEvent e)
                    System.out.println( textArea.getDocument().getDefaultRootElement().getElementCount() );
          scrollPane = new JScrollPane( textArea );
          getContentPane().add( scrollPane );
          getContentPane().add( new JTextField(10),BorderLayout.SOUTH );
//          textArea.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "" );
     public static void main(String[] args)
          TextAreaTest frame = new TextAreaTest();
          frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
          frame.pack();
          frame.setVisible(true);
}

Similar Messages

  • Can't set selected text in a JTextArea (bizarre)!

    I've go this method here to select text in a JTextArea is doesn't work.
    Any ideas?? I haven't posted ALL the code because there is quite a lot of it in a number of classes.
    public void selection(int i)
              String meth = methods.get(i).toString();
              String tex = tc.getText();
              int pos = tex.indexOf(meth);
              if (pos != -1) {
                   myTextComponent.setSelectionStart(pos);                myTextComponent.setSelectionEndpos+meth.length));                
         }

    Selected text is only shown when the text component has focus. Assuming you are clicking on a button to invoke your code you would need to reset focus on the text field:
    myTextComponent.requestFocus();

  • How to write selected text in JTextArea in selected location

    iam using JTextArea ...
    i want to writer selected text in selected location,,,,,,

    use
    JTextArea.getSelectedText() and
    JTextArea.replaceRange(String str, int start, int end)
    methods.

  • SetFont for selected text in JTextArea

    Hi there,
    I'm trying to build a small Texteditor.
    How do you set a selceted area of text to fx. BOLD font?
    I can of course set the font for the whole JTextArea via the setFont method, but what about a smal selection.
    Also: setFont seems to take no less than 3 arguments (fontname, style, size). Is it possible just to set the selected font as the same as before, but BOLD??
    Kind Regards
    Thomas

    Alright, so here I go :
    I've been working for two months on a TextEditor/HTMLEditor, but I'm not allowed to share my code (I work for a company that wants to use this editor).
    There are a lot of stuff that you should know about "javax.swing.text" package if you want to get initiated to Editors programming with Swing components.
    Well, first of all, I'm going to answer to your punctual question :
    You can't set style attributes ( color, bold, italic, ...) to specifc text elements in a JTextArea, you have got to use a JEditorPane or a JTextPane. (JTextPane lets you deal with the notion of "Styles"... but this is a bit complex for a simple editor, so I suggest you to just stick to the JEditorPane).
    Any of these three Components has a document model related to it. These document models can be of different types. For example, PlainDocument, StyledDocument, HTMLDocument, etc...
    A JTextArea can only have PlainDocument bound to it. These documents don't keep info about color, font, bold, and stuff for specific portions of text.They apply it to all content.
    JEditorPane can have PlainDocuments, HTMLDocuments and I think they can have StyledDocuments.
    To set bold to selected text you've got to do this :
            import javax.swing.text.*;
            int posStart = editorPane.getSelectionStart( );
            int posEnd =  editorPane.getSelectionEnd( );
            int selLength = posEnd - posStart;       
            MutableAttributeSet atr = new SimpleAttributeSet();
            StyleConstants.setBold(atr,true);
            StyledDocument doc = editorPane.getDocument();
            //Check out false in the following instruction
            // it means that any other attribute existing should
            // be kept if it has not be redefined in the attribute you are applying
            doc.setCharacterAttributes(posStart,selLength,atr,false);         That's it.. that's the way to do it.. the same principle applies for any other attribute,
    for example if you also wanted to change font you could have added the following :
            StyleConstants.setFontFamily(atr,"Arial");Alright, so know I'm going to give you the good adresses to learn stuff about Editors, here I go:
    * The Swing Connection Articles (hard to understand for a newbie but really helpful ):
    http://java.sun.com/products/jfc/tsc/articles/index.html (Check out the TextPackage Articles)
    * Manning Matthew Robinson and Pavel Vorobiev Swing book (it's all online for free)
    This is the absolute reference, step by step examples. Check out Chapter 20 : Constructing a
    Word Processor. (This is I guess the best stuff available online about constructing Text and HTML Editors in Java with Swing)
    http://www.spindoczine.com/sbe/

  • CR duplication when Copy/Pasting text from a JTextArea

    I have a typical scenario of having text in a JTextArea. When I select some of that text and try to paste it either to an external text editor or even in the same JTextArea, I am getting extra line spaces in the screen.
    For example, if I have the following text:
    <a id=1>
       <b/>
    </a>When I copy paste it, I get:
    <a id=1>
       <b/>
    </a>When I looked to see what characters were being used for the CR, I see "\r\n". This is the standard line.seperator for Windows OS which is fine. When I save this text to a file using the Java I/O libraries, it is fine (no extra lines). But when copy/pasting it prints extra lines.
    Has anyone had similar problems?

    Has anyone had similar problems? No. How are you doing the copy/paste? Did you write your own routines or are you using the default Actions. By default, when a Document is loaded it will convert the "\r\n" end of line string to "\n" and store the single character in the Document. When you use the getText(..) method the enod of line string will be expanded to "\r\n" on a Windows system, but this should not happen in a copy/paste operation. How do you add data to your text area?
    This section from the Swing tutorial on "Text Component Features" has a working example of using copy/paste:
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html

  • How can i turn a part of a text of  a JTextArea into bold??

    how can i turn a part of a text of a JTextArea into bold?? I mean i just want the selected text to do so and not all of the content of the JTextArea.
    Is there a way to do so??
    If not, is there another component that i can use to do so??
    [Rik]

    Use a JTextPane. Here's an example to get you started:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=342068

  • How can I center text in a JTextArea?

    I'm coding my own little font selection frame, and want to display the sample text in a JTextArea, and want to know how I can get the text centered in the field. Does anyone know how this can be done? Thanks.

    Thanks Camrick, I'm disappointed that it will take so much to accomplish this. But I'm very appreciative of your response, and I will definitely put that code to use. Just not in time to turn in my assignment, lol. But thats ok, this function was beyond the requirements anyway, I just wanted to put in some bells and whistles.
    Cheers!

  • Change mouse pointer over selected text

    I have a JTextArea and i want to change the default mouse pointer to the arrow pointer when the user points to a selected text. Just like the way JCreator works.!
    Thanx

    Try this :
    Cursor textCursor = new Cursor(Cursor.TEXT_CURSOR);
    Cursor arrowCursor = new Cursor(Cursor.DEFAULT_CURSOR );
    textArea.setCursor(textCursor);
    textArea.addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseMoved(MouseEvent e) {
              int location = textArea.viewToModel(e.getPoint());
              if (textArea.getSelectionStart()<=location && location<textArea.getSelectionEnd()) {
                   if (textArea.getCursor() != arrowCursor) {
                        textArea.setCursor(arrowCursor);
              else {
                   if (textArea.getCursor()==arrowCursor) {
                        textArea.setCursor(textCursor);
    });I hope this helps,
    Denis

  • Delete selected text

    How can I mark text in a JTextArea and delete the text with a JButton? Without pushing delete on the keyboard?

    u can use this to delete the text, it will work as a delete key functionality:
    and u can select the text programmaticaly with select(startIndex, endIndex) method
    int dot = textarea.getCaret().getDot();
    int mark = textarea.getCaret().getMark();
    if(dot != mark)
    textarea.getDocument().remove(Math.min(dot, mark), Math.abs(dot - mark));
    else if(dot > 0)
    textarea.getDocument().remove(dot - 1, 1);

  • How do I select everything inside a JTextArea?

    I believe I have to do this:
    textarea.selectAll();
    But it doesn't show graphically that all the text is selected inside the JTextArea, and I want to show that to the user....
    Help????
    V

    If the text area does not have focus is does not paint the selected text. That's two for two...
    I was invoking that code in a button's click event, so that the JTextArea lost focus when a user clicked on the button...
    Thanks,
    V

  • Select problem in the JTextArea

    Hi
    I have a problem on the select(), I am trying to select multiple lines of text in the JTextArea, but select(int start, int end) can only select single line, int end will be cut to the length of the line instead of going to the next line. Can anyone give me any advice?
    Thanks in advance

    DefaultHighlighter highlighter = (DefaultHighlighter)textArea.getHighlighter();
    highlighter.setDrawsLayeredHighlights(false);

  • How can we get the selected line number from JTextArea ?

    how can we get the selected line number from JTextArea ? and want to insert line/string given line number into JTextArea??? is it possible ?

    Praitheesh wrote:
    how can we get the selected line number from JTextArea ?
    textArea.getLineOfOffset(textArea.getCaretPosition());
    and want to insert line/string given line number into JTextArea??? is it possible ?
    int lineToInsertAt = 5; // Whatever you want.
    int offs = textArea.getLineStartOffset(lineToInsertAt);
    textArea.insert("Text to insert", offs);

  • Can no longer select text in email template or read only field with mouse using IE or Firefox?

    Hi Guys,
    I can no longer select text in email template or read only field using my mouse in IE or Firefox anymore. We are using CRM 2011 rollup 18 applied with IE 11 and the latest version of Firefox. We only applied roll up 18 in Feb when this issue began.
    Thanks
    Dave
    David Kelly

    When you have a problem with one particular site, a good "first thing to try" is clearing your Firefox cache and deleting your saved cookies for the site.
    (1) Bypass Firefox's Cache
    Use Ctrl+Shift+r to reload the page fresh from the server.
    (You also can clear Firefox's cache completely using:
    orange Firefox button ''or'' Tools menu > Options > Advanced
    On the Network mini-tab > Cached Web Content : "Clear Now")
    (2) Remove the site's cookies (save any pending work first) using either of these. While viewing a page on the site:
    * right-click and choose View Page Info > Security > "View Cookies"
    * Alt+t (open the classic Tools menu) > Page Info > Security > "View Cookies"
    Then try reloading the page. Does that help?
    These features rely on JavaScript, and it sounds as though you have scripting enabled if you get (the wrong) color changes. Some add-ons might alter the way scripts operate, so a standard diagnostic to bypass interference by extensions (and some custom settings) is to try Firefox's Safe Mode.
    First, I recommend backing up your Firefox settings in case something goes wrong. See [[Backing up your information]]. (You can copy your entire Firefox profile folder somewhere outside of the Mozilla folder.)
    Next, restart Firefox in Firefox's Safe Mode ([[Safe Mode]]) using
    Help > Restart with Add-ons Disabled
    In the dialog, click "Start in Safe Mode."
    If those features work correctly, this points to one of your extensions or custom settings as the problem.
    To also disable plugins, you can use this page:
    orange Firefox button ''or'' classic Tools menu > Add-ons > Plugins category
    Any change?

  • Select text from all_views returns an empty string

    My application allows the user to select between the Data Provider for ODBC and the Data Provider for Oracle. (ODP)
    When using the ODBC provider the statement:
    Select text from all_views where view_name='MYVIEW'
    returns the expected string.
    If I connect via ODP however it returns an empty string.
    (If I use 'Select *' it tells me the text_length is 154 in this specific case - so there is definately text available.)
    I'm thinking it has something to do with the fact that the data type is LONG.
    In both cases I retreive the data using rdr.GetChars(), which should work.
    If I use the dbms_metadata.get_ddl function instead, it does return the string (Probably because the return type is not LONG)
    Unfortunately that function only works for Views in the current schema, while the original Select works for any view.
    (And I dont know what version of Oracle this function was added in - I have to support older versions too.)
    Similarly, if I use one of the XML functions to retreive the text as XML it works fine.
    (Again it is probably returned as a VARCHAR2 instead of a LONG.)
    The strange thing is that when I created my own table containing a LONG column I was able to load and retreive data without any problems.
    The problem appears to be specific to this column in all_views.
    Anyone know a solution to this?
    Thanks
    Mike

    Thanks that was it.
    I had not seen those properties since I am working with the 'generic' objects (DbCommand rather than OracleCommand, etc.)
    What is strange is that I was able to retreive data from my own LONG column WITHOUT setting this value to -1.
    (It defaulted to 0 in both cases.)
    The only difference was that when I retreived data from my own column I specified CommandBehaviour.SequentialAccess.
    When I retreived the all_views.text column I did not specify a behaviour at all.
    However the Oracle docs said that SequentialAccess is not supported ... so I guess that is not correct.
    (Maybe it doesn't 'work', but it certainly seems to cause things to work differently)
    Thanks
    Mike

  • Print/Save Selected Text to PDF

    I want to use Mozilla Firefox very much for a long time. I like it because the UI is very clean, easy to use, the icon vey pretty. When I use in my Android Mobile, it is very easy and intelligent to select content of page site. Very good!
    But I had to install Chrome instead so I've always been using "Print a selected content to PDF" but I couldn't find ways to do that with Firefox. Chrome is doing very good.
    I searched all add-ons, pdf printer software but they are only saving or printing all the page (website) to PDF.
    Please help me the ways to save a selected content to PDF. Thanks very much.

    Hii hanh01001..
    I think i know one solution to the problem
    https://addons.mozilla.org/en-US/firefox/addon/print-selected-text/?src=api
    this is an add on that is used to print the selected text only..
    have a nice day :) :)
    ---Thanks tracy :)

Maybe you are looking for