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();

Similar Messages

  • How to set selected text on JTextPane ?

    I need to set selected text on a JTextPane. I used setSelectionStart(); and setSelectionEnd(); but it doesn't work.
    Can anybody help me?

    I'm not sure if this is what you are looking for, but the following code sample was revised from the tutorial TextSamplerDemo.java. It will hightlight the word "selected" in yellow in the JTextPane.
    //created with j2sdk1.4.0_01
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;      
    public class SelectedText extends JFrame {
        public SelectedText() {
            super("Selected Text");       
            //Create a text pane.
            JTextPane textPane = createTextPane();
            JScrollPane paneScrollPane = new JScrollPane(textPane);
            paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            paneScrollPane.setPreferredSize(new Dimension(250, 155));
            paneScrollPane.setMinimumSize(new Dimension(10, 10));
            Container pane = getContentPane();
            pane.add(paneScrollPane);
        private JTextPane createTextPane() {
            JTextPane textPane = new JTextPane();
            String[] initString =
                    { "This is the ", //regular
                      "selected",     //selected
                      " text. "       //regular
            String[] initStyles = {"regular", "selected", "regular"};
            initStylesForTextPane(textPane);
            Document doc = textPane.getDocument();
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    textPane.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text.");
    return textPane;
    protected void initStylesForTextPane(JTextPane textPane) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = textPane.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = textPane.addStyle("selected", regular);
    StyleConstants.setBackground(s, Color.YELLOW);
    public static void main(String[] args) {
    JFrame frame = new SelectedText();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    S.L.

  • 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?

  • Can no longer select text in Preview

    Hello there,
    A very annoying problem: I selected some text in a .pdf file that was opened with Preview and I marked it yellow, however once I saved it I could no longer select any more text, it is like the function has disapeared. I even tried restarting the computer, but I can no longer select text in that file. How odd?
    Funny enough, the phenomenon doesn't occur with all my .pfd files. I guess it is a bug, but quite annoying. Any one else having the same problem?

    Thanks for posting back though i'm sorry it didnt work.
    I believe there are also other dashboard plist files in that folder (i'm not currently at my Mac so can't say which exactly, though i believe one is called "client"). You could try trashing them (or dragging them to the desktop).
    Does the problem also happen if you log in to another account? Create a new account if necessary.
    /p

  • How can i set predictive text to a foreign language

    I'm new to apple and iPhones. I've got everything setup in English but I frequently want to send text and/or email messages in French. When I do this predictive text jumps in and changes things to what it thinks I want in English. e.g. if I type tous it predicts I want toys and inserts it accordingly. How can I set predictive text to a foreign language.
    (p.s. my wife's iPad works fine as it has a button to press for alternative language but I don't see anything similar for iPhone)

    Add the French keyboard.
    Settings > General > Keyboard > Keyboards > Add > French

  • How to set selected text color in Spark TextInput

    I'm trying to make Spark TextInputs and MXFTETextInputs look like Halo/MX TextInputs as much as possible, since I have a mix of both Spark and MX TextInputs in my application. I know I can set the
    selection background color to black using focusedTextSelectionColor. How can I set the selected text color to white so it matches the MX white-on-black look?

    This works, if you set the enabled property directly on the s:TextInput:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx">
        <s:layout>
            <s:VerticalLayout horizontalAlign="center" verticalAlign="middle" />
        </s:layout>
        <s:controlBarContent>
            <s:CheckBox id="ch" label="enabled" selected="true" />
        </s:controlBarContent>
        <fx:Style>
            @namespace s "library://ns.adobe.com/flex/spark";
            @namespace mx "library://ns.adobe.com/flex/mx";
            s|TextInput:disabled {
                color: red;
        </fx:Style>
        <s:Group>
            <s:TextInput id="ti" text="The quick brown fox jumps over the lazy dog" enabled="{ch.selected}" />
        </s:Group>
    </s:Application>
    It can get a bit trickier when you're setting the enabled property on a parent container, since (I believe) that the child control's enabled properties are still set to true and just the container is disabled. One possible workaround would be to bind the child TextInput control's enabled property to the container's enabled property. That way the s:TextInput should still go to it's disabled state and you can customize the disabled state's styles to have darker text, or whatever else you want.
    <s:Group id="gr" enabled="{ch.selected}">
        <s:TextInput id="ti" text="The quick brown fox jumps over the lazy dog" enabled="{gr.enabled}" />
    </s:Group>
    Peter

  • 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);
    }

  • Set selected text as variable (CS3 with JS)

    How can I set a piece of selected text as a string variable?
    I'm running InDesign with InCopy CS3 on a Windows XP computer.

    If you mean "assign the selected text to a variable", then you could do this:
    var myText = app.selection[0].contents;
    Peter

  • JTextPane - setting selected text colour

    Ok, I have a bit of a problem. Here is some general information about my program.
    I have a JTextPane called "DDITextArea" and I can type in it and stuff. I want to be able to select some of the text and use a JColorChooser to set the text to that color of my choice. I am doing a bit of experimentation with the swing components and messed around with a JColorChooser. Here is the code for the chooser.
        ColourOption.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (first) {
              first = false;
              chooser.setPreviewPanel(new CustomPane());
            JDialog dialog = JColorChooser.createDialog(RecipeBrowser.this, "Demo 3", true, chooser, new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                    c = chooser.getColor();
                }, null);
            dialog.setVisible(true);
    *I NEED SOMETHING HERE TO SET THE SELECTED TEXT TO THE COLOUR I CHOOSE WITH THE JCOLOURCHOOSER
    *I HAVE A JTEXTPANE AND I WANT TO BE ABLE TO SELECT SOME TEXT THEN USE THE JCOLORCHOOSER TO SET THE COLOUR OF THE SELECTED TEXT
        });as you can see from the comments near the end of the code sample, I need to know how to set the selected text to Color c. I don't know if there is a method for this. I looked at the online Java syntax database but to no luck. Just to ensure that there is no misunderstanding I will give an example:
    DDITextArea has the sentence "The dog is wet and smelly" and its default font colour is black. If I highlight the words "The Dog", open the ColorChooser and select red, the words "The Dog" will be red while everything else is black.
    If it is any help, here is where my DDITextArea is created
              final JTextPane DDITextArea = new JTextPane();
              JScrollPane DDITextAreaScrollPane = new JScrollPane(DDITextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              //DDITextArea.setLineWrap(true);
              //DDITextArea.setWrapStyleWord(true);
              DDITextArea.setEnabled(true);
              DDITextArea.setEditable(true);
              DDITextArea.setVisible(true);
              gbc.fill = GridBagConstraints.BOTH;
              gbc.anchor = GridBagConstraints.CENTER;
              gbc.gridx = 1;
              gbc.gridy = GridY;
              gbc.gridwidth = 1;
              gbc.gridheight = 1;
              gbc.weightx = 1;
              gbc.weighty = 1;
              gbl.setConstraints(DDITextAreaScrollPane, gbc);
              PrintTab.add(DDITextAreaScrollPane);Am I missing any necessary syntax to do this or is there something much more complicated involved?

    Sorry for the double post but I figured it out. I missed the answer. This is a clear sign I must stop doing past-midnight research.
    Anyways, for any folds that have trouble with this in the future, here you go. I hope someone, somewhere, sometime, will have need for this.
        ColourOption.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (first) {
              first = false;
              chooser.setPreviewPanel(new CustomPane());
            JDialog dialog = JColorChooser.createDialog(RecipeBrowser.this, "Demo 3", true, chooser, new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                    c = chooser.getColor();
                }, null);
            dialog.setVisible(true);
    //THE CODE BELOW THIS COMMENT IS WHAT I ADDED
    new StyledEditorKit.ForegroundAction("", c).actionPerformed(null);
    //THE CODE ABOVE THIS COMMENT IS WHAT I ADDED
        });

  • How can I set the text feild in a form to print out the entire feild?

    Right now it's only printing out what shows in the box, I want the box to expand when printed and show all the text entered in the field, how can I set it to do that?

    I think that the font size has to be set in the form itself, not the FDF.

  • How can I change selection texts of standard report (S_P99_41000192)?

    Hi:
    I want to change selection texts of  tcode s_P99_41000192.
    ( Our SAP verison is SAP 4.7 version, non unicode)
    Because we can see only Deutch.
    It looks standard sap query so we can not add it into package.
    How can we change it?
    Please help me.

    Hi,
    you can change this in the related InfoSet /SAPQUERY/AM27 on which the Query is based on. Tcode InfoSet maintenance is SQ02.
    Regards,
    Markus

  • Can I set the text color in a Label?

    Hi everyone ~
    Can I set the font color in PP? I only found that there is a "setBackground".. but I want to set the color within a Label.
    Thanks!
    Gary

    Fixed it!
    There was a global style for s|Label and since the Spark button uses one of these for the text, that was it.

  • Using the States Example how can I set Selected to Maryland Without RowNumber

    Let's use the states example for the sake of everyone having
    the code in front of them. If I am returning a value from the
    database that I am writting out to the application like this
    <%out.write("STATE_NAME"); %>
    how can I set the selected value to that without knowing what
    the row number is, here is my try but I get a few error messages:
    <option spry:if="{name} == '<%out.write("STATE_NAME");
    %>'" value="{name}" selected
    ="selected">{name}</option>
    <option spry:if="{name} != '<%out.write("STATE_NAME");
    %>'" value="{name}" >{name}</option>
    I get double the states and the following in the debug box:
    Caught exception in Spry.Data.Region.prototype.processTokens
    while evaluating: Alabama == Exception:[object Error]
    Caught exception in Spry.Data.Region.prototype.processTokens
    while evaluating: Alabama != '' Exception:[object Error]
    This goes on for as many records as I have in the DB,
    Please let me know how it could be done if it could be done?

    I believe what you guys are looking for is the
    Set
    Default Row Based on Specific Column sample that is on the
    Spry
    Samples Page.
    The problem of using a spry:if="{name} ..." approach is that
    it only makes sure the form select widget is set to what the server
    thinks is the current row in the data set, but it doesn't actually
    set the current row in the data set to reflect this, so the cities
    select is out of sync cause it is defaulting to displaying the
    cities for the first row in the states data set.
    Checkout the sample I mentioned above, it will show you how
    to set up an observer where you can query for the correct row
    immediately after the data is loaded, and then set the current row
    so that everything is as expected.
    --== Kin ==--

  • SetCharacterAttributes sets selected text to p-implied tag

    I am trying to remove all font attributes from the selected text. I have used the setCharacterAttributes with the replace option set to true for both the TextPane and the EditorKit. The result is the selected text is changed to "<p-implied>". If I set the replace option to false the method works as advertised but this doesn't help me. I have not been able to find any such beast in previously asked questions. Any ideas?
    Steve

    If you still do not have solution try this :
    SimpleAttributeSet a = new SimpleAttributeSet(getInputAttributes());
    a.removeAttribute(CSS.Attribute.FONT);
    setCharacterAttributes(a, true);

  • How can I assign a text file to JTextArea component??

    Hi every body, does any boody has a code for read a text file and show this text in a JTextArea??? I'm trying with a FileReader but the text doesn't appear well.
    Thanks in advance.
    Juan

    String s = "";
    BufferedReader reader =
                             new BufferedReader(new FileReader(path));
                        String temp = reader.readLine();
                        s += temp + "\n";
                        while (temp != null)
                             temp = reader.readLine();
                             if (temp != null)
                                  s += temp + "\n";
                        reader.close();
    textArea.setText(s);

Maybe you are looking for

  • Syncing Google Gmail Contacts with Address Book and iPhone Contacts

    Can anyone recommend a good way to sync Google Gmail Contacts with the Address Book on the Mac and with Contacts on the iPhone? I tried using ABGMerge, but could not get it to work so and am looking for other options. Thanks.  PowerBook G4, Macintos

  • 2 Hash tables ??

    hello, i have a problem when i run the following code and enter an element eg AU it displays gold, but when i type AU1 (i.e Au and 1 atom) it displays the follwing message, not recongising either element or atom occurance, im not sure weather the pro

  • XI 2.0

    Hi All, anyone who is working on XI 2.0 please give me some idea of what adapters used in 2.0 and if u have any info regarding IDOC and RFC adapters please provide me... ( as i searched in sdn but i didnt get enough information).. regards Kumar

  • Cant find my library.

    I have about 5 days worth of music (itunes & other) on my library, but after the latest update they have all gone except my purchases from Itunes. Can anyone explain why and how I can upload my music again. Thanks.

  • URGENT!Problem running a Query with a Subquery that includes the same table

    Hello all, Currently we are working over Oracle Database 10g Release 2 (10.2.0.3) Patch Set1. We have registered a schema called ICRI and we have created two VIEW over this schema to work in some occasions. CREATE OR REPLACE VIEW "ICRI_RELACIONAL_VIE