Select higlighted text in JTextArea

Hello,
I am developing a swing application and have a JTextArea included. In the JTextArea I highlight one or more words with the addHighlight method. Now the user should also be able to select text, especially the highlighted text. But when I select some highlighted text, it does not change the color, so the user is not aware that he selected text.
How can I implement the intended behaviour?
Thanks in advance
Sandra

1) Change the style of highlights so that both highlights are painted:
DefaultHighlighter highlighter =  (DefaultHighlighter)textComponent.getHighlighter();
highlighter.setDrawsLayeredHighlights(false);2) You need to use a different color highlighter to distinguish the highlighted text from the selected text:
Highlighter.HighlightPainter cyanPainter =
    new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
textComponent.getHighlighter().addHighlight( 8, 15, cyanPainter );

Similar Messages

  • Selecting multiple text in JTextArea

    Howdy Java folks! I've been busting my butt trying to select more than one piece of text in a JTextArea. For example, I would like to:
    textArea.select(0, 4); // and then select another piece of text
    textArea.select(7, 9); // and show both text snippets highlighted
    But I would like to keep both and possible more pieces of text highlighted. The 2nd select() will override the first thus only showing the last area selected.
    Can anyone point me in the right direction? Thanks a mucho.

    Try this. It selects vertical block of text.
    best regards
    Stas
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    public class Test
    JFrame frame;
    JTextArea ta;
    public static void main(String args[])
    new Test();
    public Test()
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ta=new JTextArea("test11111\ntest22222\ntest33333\ntest44444\ntest55555\n");
    ta.setCaret(new Caret_());
    JScrollPane scroll=new JScrollPane(ta);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(scroll,BorderLayout.CENTER);
    JButton copy=new JButton("Copy");
    ActionListener lst=new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    try {
    Highlighter.Highlight[] selections= ta.getHighlighter().getHighlights();
    String text="";
    int cnt=selections.length;
    for (int i=0; i<cnt; i++) {
    int start=selections.getStartOffset();
    int end=selections[i].getEndOffset();
    String selectedText=ta.getDocument().getText(start,end-start);
    text+=selectedText+'\n';
    System.err.println(selectedText);
    StringSelection ss=new StringSelection(text);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
    catch (Exception ex) {
    ex.printStackTrace();
    copy.addActionListener(lst);
    frame.getContentPane().add(copy,BorderLayout.SOUTH);
    frame.setSize(300,200);
    frame.setVisible(true);
    class Caret_ extends DefaultCaret {
    Point lastPoint=new Point(0,0);
    public void mouseMoved(MouseEvent e) {
    super.mouseMoved(e);
    lastPoint=new Point(e.getX(),e.getY());
    public void mouseClicked(MouseEvent e) {
    super.mouseClicked(e);
    getComponent().getHighlighter().removeAllHighlights();
    protected void moveCaret(MouseEvent e) {
    Point pt = new Point(e.getX(), e.getY());
    Position.Bias[] biasRet = new Position.Bias[1];
    int pos = getComponent().getUI().viewToModel(getComponent(), pt, biasRet);
    if(biasRet[0] == null)
    biasRet[0] = Position.Bias.Forward;
    if (pos >= 0) {
    setDot(pos);
    Point start=new Point(Math.min(lastPoint.x,pt.x),Math.min(lastPoint.y,pt.y));
    Point end=new Point(Math.max(lastPoint.x,pt.x),Math.max(lastPoint.y,pt.y));
    customHighlight(start,end);
    protected void customHighlight(Point start, Point end) {
    getComponent().getHighlighter().removeAllHighlights();
    int y=start.y;
    int firstX=start.x;
    int lastX=end.x;
    int pos1 = getComponent().getUI().viewToModel(getComponent(), new Point(firstX,y));
    int pos2 = getComponent().getUI().viewToModel(getComponent(), new Point(lastX,y));
    try {
    getComponent().getHighlighter().addHighlight(pos1,pos2,((DefaultHighlighter)getComponent().getHighlighter()).DefaultPainter);
    catch (Exception ex) {
    ex.printStackTrace();
    y++;
    while (y<end.y) {
    int pos1new = getComponent().getUI().viewToModel(getComponent(), new Point(firstX,y));
    int pos2new = getComponent().getUI().viewToModel(getComponent(), new Point(lastX,y));
    if (pos1!=pos1new) {
    pos1=pos1new;
    pos2=pos2new;
    try {
    getComponent().getHighlighter().addHighlight(pos1,pos2,((DefaultHighlighter)getComponent().getHighlighter()).DefaultPainter);
    catch (Exception ex) {
    ex.printStackTrace();
    y++;

  • JTextArea artifacts when selecting/deselecting text

    I just bumped up against a font rendering issue with JTextArea. I have no doubt that it's a bug, but does anyone know of a workaround?
    Run the program below and select/deselect text by double-clicking words. The text is painted in a different location when selected and deselected. Try selecting by dragging the mouse or pressing shift and left/right arrow keys -- same problem, but the actual pixel location of the artifacts sometimes differs depending on the selection start and end, and the way the text was selected (keyboard/mouse drag/double click).
    Now try selecting the last word ("dog") by double clicking.import java.awt.Font;
    import java.awt.font.TextAttribute;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    public class TextAreaProblem {
      public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new TextAreaProblem().makeUI();
      public void makeUI() {
        Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
        attributes.put(TextAttribute.FAMILY, "Arial");
        attributes.put(TextAttribute.SIZE, 36.0);
        attributes.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
        attributes.put(TextAttribute.TRACKING, TextAttribute.TRACKING_LOOSE);
        Font font = Font.getFont(attributes);
        font = font.deriveFont(attributes);
        final JTextArea textArea = new JTextArea("The quick brown fox jumps over the lazy dog.");
        textArea.setFont(font);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(textArea));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(850, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    Microsoft Windows [Version 6.1.7600]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
    C:\Users\Darryl>java -version
    java version "1.6.0_17"
    Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
    Java HotSpot(TM) Client VM (build 14.3-b01, mixed mode, sharing)Any tips for a workaround will be much appreciated.
    Thanks, Darryl

    The fix using System.setProperty worked 100% for all font and attribute combinations I tried -- thanks again.
    2) Does it work to set the property after the GUI is already created and shown? (shall test that myself in a few hours, but would be nice to know earlier :)No. However, you may set this property as a component client property (on the JTextComponent), but before that component is made visible.This didn't work for me. I tried both putClientProperty and getDocument().putProperty, as suggested in the other thread. What did I miss?import java.awt.Font;
    import java.awt.font.TextAttribute;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    public class TextAreaProblem {
      public static void main(String[] args) throws Exception {
        //System.setProperty("i18n", Boolean.TRUE.toString());
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new TextAreaProblem().makeUI();
      public void makeUI() {
        Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
        attributes.put(TextAttribute.FAMILY, "Arial");
        attributes.put(TextAttribute.SIZE, 36.0);
        attributes.put(TextAttribute.TRACKING, TextAttribute.TRACKING_LOOSE);
        attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        Font font = Font.getFont(attributes);
        font = font.deriveFont(attributes);
        final JTextArea textArea = new JTextArea("The quick brown fox jumps over the lazy dog.");
        textArea.setFont(font);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        // tried either or both -- didn't help
        textArea.getDocument().putProperty("i18n", Boolean.TRUE.toString());
        textArea.putClientProperty("i18n", Boolean.TRUE.toString());
        JFrame frame = new JFrame();
        frame.add(new JScrollPane(textArea));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(850, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }Darryl
    edit Setting this property seems to remove the ability to render underlined and strikethrough attributes. Changed the code above to add these. When "i18n" is set, they are ignored.
    edit2 GlyphPainter2 also doesn't appear to support foreground/background colors and swap_colors. It's beginning to look like whoever wrote that class solved a single problem of cumulative integer math error but introduced several others. Or maybe just didn't reimplement the features that weren't inherited..
    Edited by: DarrylBurke on Sep 8, 2010 5:13 AM

  • Set text of jtextArea to a text file

    I have tried everything in trying to let the user select a text file using jfilechooser and then set the text of a jtextArea as the text file. Nothing has worked so far, so all I have right here is the basic functionality of choosing the file.
    If someone could show me a good way to read the whole text file and put that text into a jtextArea, I would really appreciate it.
    Since nothing has worked all I have is this:
    JFileChooser chooser = new JFileChooser();
         int returnVal = chooser.showOpenDialog(this);
         String getFile = chooser.getSelectedFile().getPath();

    ... followed by theJTextArea.read(new FileReader(getFile), null);

  • 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't select vertical text formatting since Win 7

    Please help.
    Have recently upgraded to win 7 and now I cannot select any text formatting options in the drop down text menus. I can see them, but the drop down menu buttons don't work.
    Has anyone had this happen?
    I have spent so much time on the computer and it's so hard to get any work done.
    Advice would be much appreciated
    I would like to go back to XP but the computer guy says that's not possible.
    Thanks
    ZeeBud

    Thank you so much for responding Peter. I feel one step closer to being able to get my work done.
    Your solution means that I can now use the tools in the tools palette, but no luck with being able to use the text selection drop down menus.
    It's quizzical. I can select the fonts by clicking through file the file path> type> font. Just not through drop downs.
    Any thoughts anyone?
    Zj

  • Using the CTRL button to select multiple text segments in Design Editor

    Hi there,
    This may be a fairly elementary question, however I'm very new to RoboHelp.
    I'm currently building an online help text system, and when formatting my html files in Design Editor, I have to apply styles one at a time. I was hoping RoboHelp would have a function identical to Microsoft Word whereby holding down the CTRL key would allow you to select various segments in the file and apply the style. Eg. selecting only text you want to apply Heading 3 to.
    If RoboHelp does not have this functionality, this project will take me in the vicinity of 7 years to complete. Thanks for your time.
    Regards,
    PK

    No it doesn't work that way. What you need to do is create some character styles in your style sheet and apply those.
    Paragraph styles are defined something like
    P {
        font-size: 10pt;
        margin-top: 0pt;
        margin-bottom: 6pt;
        font-family: Verdana, sans-serif;
        color: #000000;
        font-weight: normal;
    P.Normal-Indent {
        margin-left: 20pt;
    where the second P definition will inherit all that is in P plus add the indent.
    When you select those styles, they will be applied to the whole paragraph.
    You can also create characters classes. If you do it within RoboHelp, RH will write the CSS code for you. If you edit the CSS outside RH, then instead of writing P or some other tag, you would normally start with the full stop so you might have
    .code {
        font-size: xx-small;
        font-family: Courier;
    to apply the Courier font to a selection in any paragraph style.
    In RoboHelp you need to prefix the character code with "span" to make it display in the dropdown, thus you would need:
    span.code {
        font-size: xx-small;
        font-family: Courier;
    See www.grainge.org for RoboHelp and Authoring tips

  • I'm having problems (1)selecting onscreen text, (2) having problems resizing menu boxes and selecting menues with the cursor. I'm not able to select menus and move them. I'm not sure how to correct this.

    I'm having problems (1) selecting onscreen text, (2) resizing menu boxes and selecting menues with the cursor. I'm not able to select menus and move them. I'm not sure how to correct this.

    1) This is because of software version 1.1. See this
    thread for some options as to how to go back to 1.0,
    which will correct the problem...
    http://discussions.apple.com/thread.jspa?threadID=3754
    59&tstart=0
    2) This tends to happen after videos. Give the iPod a
    minute or two to readjust. It should now be more
    accurate.
    3) This?
    iPod shows a folder icon with exclamation
    point
    4) Restore the iPod
    5) Try these...
    iPod Only Shows An Apple Logo and Will Not Start
    Up
    iPod Only Shows An Apple Logo
    I think 3,4, and 5 are related. Try the options I
    posted for each one.
    btabz
    I just noticed that one of the restore methods you posted was to put it into Disk Mode First rather than just use the resstore straight off, I Have tried that and seems to have solved the problem, If it has thank you. previously I have only tried just restoring it skipping this extra step. Hope my iPod stays healthy, if it doesnt its a warrenty job me thinks any way thanks again

  • How to Print Text in the PLD when we select Type : Text

    Hi All
    I designed a PLD for Purchase Order which is working well but
    whenever we select type: Text and we enter some text in the row level for each item. when we see the PLD priview
    Items are displaying but the text below the items are not displaying
    it displays an empty row after each item
    How should i print text in the PLD
    I required in this following Format
    ITEMCODE  DESCRIPTION      QTY
    001              XYZ                      20
    this is capital Good Item
    002             PQR                        30 
    this is Raw Material
    In this above format
    I didnt get the text below the Items
    Can any one suggest the correct answer

    Thanks for your reply
    I already select the linetext field from table POR10 and kept it  in the PLD
    but i didnt get my required format
    after giving that line text field  iam getting
    in this way
    S.No.        ITEMCODE   DESCRIPTION  QTY
       1               001               XYZ                 20
    this is Capital Goods
      2                                                                 
    this is Capital Goods
    the text is repeating twice
    I Put the ItemDescription field  in POR1 and Line Text Field in POR10 in the same repetitve area

  • How do I select multiple text in Pages

    I'm using the newest version of pages.
    In MS office WORD, I can hold the Ctrl key and with multiple klick in the text I can select multiple text.
    Does pages has the similar function?

    Not possible in Pages 5.2.2, this has been removed by Apple along with 110 features.
    In Pages '09 you hold down the command key, the exact same equivalent as in Word for Windows.
    Peter

  • How to print diffrent color and diffrent size of text in JTextArea ?

    Hello All,
    i want to make JFrame which have JTextArea and i append text in
    JTextArea in diffrent size and diffrent color and also with diffrent
    fonts.
    any body give me any example or help me ?
    i m thanksfull.
    Arif.

    You can't have multiple text attributes in a JTextArea.
    JTextArea manages a "text/plain" content type document that can't hold information about attributes ( color, font, size, etc.) for different portions of text.
    You need a component that can manage styled documents. The most basic component that can do this is JEditorPane. It can manage the following content types :
    "text/rtf" ==> via StyledDocument
    "text/html" ==> via HTMLDocument
    I've written for you an example of how a "Hello World" string could be colorized in a JEditorPane with "Hello" in red and "World" in blue.
    import javax.swing.JEditorPane;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import java.awt.Color;
    public class ColorizeTextTest{
         public static void main(String args[]){
              //build gui
              JFrame frame = new JFrame();
              JEditorPane editorPane = new JEditorPane();
              frame.getContentPane().add(editorPane);
              frame.pack();
              frame.setVisible(true);
              //create StyledEditorKit
              StyledEditorKit editorKit = new StyledEditorKit();
              //set this editorKit as the editor manager [JTextComponent] <-> [EditorKit] <-> [Document]
              editorPane.setEditorKit(editorKit);
              StyledDocument doc = (StyledDocument) editorPane.getDocument();
              //insert string "Hello World"
              //this text is going to be added to the StyledDocument with positions 0 to 10
              editorPane.setText("Hello World");
              //create and attribute set
              MutableAttributeSet atr = new SimpleAttributeSet();
              //set foreground color attribute to RED
              StyleConstants.setForeground(atr,Color.RED);
              //apply attribute to the word "Hello"
              int offset = 0; //we want to start applying this attribute at position 0
              int length = 5; //"Hello" string has a length of 5
              boolean replace = false; //should we override any other attribute not specified in "atr" : anwser "NO"
              doc.setCharacterAttributes(offset,length,atr,replace);
              //set foreground color attribute to BLUE
              StyleConstants.setForeground(atr,Color.BLUE);
              //apply attribute to the word "World"
              offset = 5; //we include the whitespace
              length = 6;
              doc.setCharacterAttributes(offset,length,atr,replace);
    }

  • Download and upload selection screen texts

    hello,
           My requirement is to upoad and download selection screen texts from one system to another..
           How do download  the selection screen texts from program to the application server and then upload them on another system. I am writing a bdc to carry out this process...
          Please help me out with this..
    Thank you,

    Hi,
      Why don't you just transport it? If it is linked you can asked basis to set the transport part and link it. If it is not you can download the transport and import it on another system.
      If you still need a program to do that. You can use SAPlink on [http://wiki.sdn.sap.com/wiki/display/ABAP/SAPlink]. SDN provided such code already just download it and implement it on both of your system then you can copy a program with selection screen.
    Cheers,
    Chaiphon

  • In a document with several sections, in section VIII and IX one cannot select the text of the page foot nor set the pointer in it; so, one cannot write nor change the page foot text. Please help!

    in a document with several sections, in section VIII and IX one cannot select the text of the page foot nor set the pointer in it; so, one cannot write nor change the page foot text. Please help!

    Question already asked and answered several times.
    It's a bug striking in long documents.
    Select a word somewhere higher in the page then use the arrows to reach the wanted insertion point.
    Yvan KOENIG (VALLAURIS, France) mardi 23 août 2011 15:44:24
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please :
    Search for questions similar to your own
    before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • Possible Bug when selecting the "text" tab on a Line Chart

    Thought I would pass this on.  Not sure if it has been logged yet or not.  Sometimes when building a line chart, the properties field locks up when I try and select the "text" tab.  The dialog boxes in the "text" tab do not show up and the "layout" tab is also highlighted.  I do not know what causes this, but it has happened to me numerous times.  The only solution is to totally delete the line chart and start all over.  It may be related to copying and pasting.  I set up a chart the way I need it and then copy/paste it rather than making all the changes on a default settings chart when I need another chart.
    Stan

    Hi Stan,
    Are you encountering this problem in the RTM version or SP1?
    Can you list the exact steps to reproduce this problem in the most simple case?
    Example:  add line chart, bind to data, copy, paste, click on text tab...............
    Thanks,
    Gerrit

  • After placing a new text box in my document, typing new text, clicking away, then coming back to edit the text, I am unable to get my cursor to reappear within that text box. I can only select the box itself. I cannot select the text. Where is my cursor?

    After placing a new text box in my document, typing new text, clicking away, then coming back to edit the text, I am unable to get my cursor to reappear within that text box. I can only select the box itself. I cannot select the text. Where is my cursor?

    Even simpler than that.
    Clicking once in a text box selects it.
    Clicking once in a selected text box places the insertion point in the box.
    The clicks do not need to be close enough in time to be read as a double click.
    The same behaviour applies to table cells in Pages and in Numbers.
    Regards,
    Barry

Maybe you are looking for