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

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.

  • 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

  • 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

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

  • Setting selected border colour of a JToggleButton

    Hi
    I am wanting to be able to change the selected border colour of a JToggleButton. I have already been able to do a similar thing for changing the selected background colour for the JToggleButton by:
    button.setUI(new MyUI(Color.gray));
    class MyUI extends javax.swing.plaf.metal.MetalToggleButtonUI
    Color color;
    public MyUI(Color c){color = c;}
    public Color getSelectColor(){return color;}
    however I want the background colour of the toggle button to remain the same whether selected or not (so I'm not using this).
    I realise that I can use a MouseListener to do this (I have already done that to change the rollover border colour), but it is more of a pain for the selected border colour, so I was wondering if anyone knew of a similar way to change the selected border colour to the above method?
    Thanks

    your layerpane lives on top of a container. set the
    background of the container.
    here is a sample code. In the createAndShowGUI you
    can add a line,
    frame.setBackground(Color.white) ;
    http://java.sun.com/docs/books/tutorial/uiswing/compon
    ents/example-1dot4/LayeredPaneDemo2.javaThe program uses JLabels on different layers to display the colours, I would prefer not to use a large white JLabel as my background.
    I have tried to set my JFrame background colour using-
    frame.setBackground(Color.white) ;It will not work for me

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

  • Problem with focus and selecting text in jtextfield

    I have problem with jtexfield. I know that solution will be very simple but I can't figure it out.
    This is simplified version of situation:
    I have a jframe, jtextfield and jbutton. User can put numbers (0-10000) separated with commas to textfield and save those numbers by pressing jbutton.
    When jbutton is pressed I have a validator which checks that jtextfield contains only numbers and commas. If validator sees that there are invalid characters, a messagebox is launched which tells to user whats wrong.
    Now comes the tricky part.
    When user presses ok from messagebox, jtextfield should select the character which validator said was invalid so that user can replace it by pressing a number or comma.
    I have the invalid character, but how can you get the focus to jtextfield and select only the character which was invalid?
    I tried requestFocus(), but it selected whole text in jtextfield and after that command I couldn't set selected text. I tried with commands setSelectionStart(int), setSelectionEnd(int) and select(int,int).
    Then I tried to use Caret and select text with that. It selected the character I wanted, but the focus wasn't really there because it didn't have keyFocus (or something like that).
    Is there a simple way of doing this?

    textField.requestFocusInWindow();
    textField.select(...);The above should work, although read the API on the select(...) method for the newer recommended approach on how to do selection.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • Report text colour

    Hi there,
    I have a report with a column which is red or green, Iwould like to set the text colour accordingly, I have an interactive report and a SQL report, does anybody know how I can do this? Thanks... Anil

    By searching the forum for all the previous posts on this topic?
    http://forums.oracle.com/forums/search.jspa?threadID=&q=%28column+OR+cell%29+AND+%28color+OR+colour+OR+hilight+OR+highlight%29+AND+conditional*&objID=f137&dateRange=all&userID=&numResults=15&rankBy=10001

  • Can't select CMYK text colour for text fields in Acrobat Pro forms?

    I have designed a business card template in Indesign, and now want to use Acrobat Pro to add in text fields so that a client can edit the contact details on the cards in future.
    I need to select a specific text colour for the fields, so that it matches the rest of the design. The cards will obviously need to be printed and the document has been set up in CMYK, but when I enter the CMYK colour breakdown in the Properties > Text Colour panel, it won't apply the colour to that field. The text either stays at the default black, or reverts to RGB - which isn't suitable for printing and doesn't match the colour I need.
    Can anybody PLEASE shed some light on this? Other similar posts have either not been answered or people have suggested JavaScript..? I have no idea what I'm supposed to do with a JS code..? Surely there's an easier explanation?
    Thanks in advance.

    This is for a text field that you create in Acrobat, whether the form is used offline or online. The script is a custom Format script, which you can place by bringing up the Properties dialog for the field, select the Format tab, set a format category of Custom, and you should see where you can enter the script. Change the string "Instructional text goes here" to the text you want to display when the field is blank.

  • How can i Change the Size of the selected text in JTextPane using ConboBox

    plzz help...
    How can i Change the Size of the selected text in JTextPane using ConboBox ???
    i m using if(cb.getSelectedItem=="small")
    cb.setAction(new StyledEditorKit.FontSizeAction("double click", 12);)
    if(cb.getSelectedItem=="medium")
    cb.setAction(new StyledEditorKit.FontSizeAction("double click", 14);)
    if(cb.getSelectedItem=="large")
    cb.setAction(new StyledEditorKit.FontSizeAction("double click", 16);)
    this code is not working properly according to the action i set on comboBox.
    when i select medium the previously set action on comboBox works like small action work.
    when i select large the medium action starts .
    means its not working in correct time when i select item of combox n action of that item is not working at that time..
    plzz plzz help me:(

    Action action1 = new StyledEditorKit.FontSizeAction(
    "double click", 12);
    Action action2 = new StyledEditorKit.FontSizeAction(
    "double click", 14);
    Action action3 = new StyledEditorKit.FontSizeAction(
    "double click", 18);
    s2 = (String) cb7.getSelectedItem();
    if (s2.equals("Small")) {
    cb7.setAction(action1);
    e1.setSource(cb7);
    } else
    if (s2.equals("Medium")) {
    cb7.setAction(action2);
    e1.setSource(cb7);
    } else if (s2.equals("Large")) {
    cb7.setAction(action3);
    // e1.setSource(cb7);
    when i chooze any combobox item then according to that item i set the Action on ComboBox but that action is not working properly on the selected text in the JTextPane..means selected text in JText Pane is not changes its Size according to the comboBox selected ITEM.
    PLZ plzzzzzzzzzz help me:((.i will be thankfull to u.

  • ComboBox Problem to change the size of selected text in JTextPane.

    hi 2 all!
    I have a problem in combo box actions, when i change the item in the combo its set is not set at that time but that action is performed when next action is taken, i have used combobox.setAction(new StyledEditorKit.FontSizeAction(" click", 12);) command to set the size of the selected text
    Plz suggest the solution also if possible,plz provide some code for this
    Action action1 = new StyledEditorKit.FontSizeAction(
                                                 "double click", 12);
                                       Action action2 = new StyledEditorKit.FontSizeAction(
                                                 "double click", 14);
                                       Action action3 = new StyledEditorKit.FontSizeAction(
                                                 "double click", 18);
    s2 = (String) cb7.getSelectedItem();
                                       if (s2.equals("Small")) {
                                            cb7.setAction(action1);
                                            e1.setSource(cb7);
                                                      } else
                                       if (s2.equals("Medium")) {
                                            cb7.setAction(action2);
                                            e1.setSource(cb7);
                                                                          } else if (s2.equals("Large")) {
                                            cb7.setAction(action3);
                                            // e1.setSource(cb7);
    when i chooze any combobox item then according to that item i set the Action on ComboBox but that action is not working properly on the selected text in the JTextPane..means selected text in JText Pane is not changes its Size according to the comboBox selected ITEM.
    PLZ plzzzzzzzzzz help me:((.i will be thankfull to u.
    thanx in advance..

    this code is not working properly according to the action i set on comboBox.Thats correct, the setAction() method is used to invoke an existing Action on the combo box, not create a new Action.
    What you need to do is have a single action that uses the information from the item that was selected to build a dynamic Action to change the font. Something like:
    public void actionPerformed(ActionEvent e)
         JComboBox comboBox = (JComboBox)e.getSource();
         int fontSize = Integer.parseInt( comboBox.getSelectedItem().toString() );
         Action fontAction = new StyledEditorKit.FontSizeAction("size", fontSize);
         fontAction.actionPerformed(null);
    }

  • How to set the desired font to the selected text in textframe?

    Hi,
    I want to change the font(let's say Times New Roman) of selected text in textframe when I click on  menu-item of my plug-in.
    I went through the Adobe Text Engine documentation and  tried some code for setting font but failed. I don't see any member function in IFont class to set desired font, so unable to move forward.
    plz see the code. I would like to know one more thing that how can we set a particular font for a textframe?
    TextRangesRef rangesRef = NULL;
    result = sAIDocument->GetTextSelection(&rangesRef);
    aisdk::check_ai_error(result);
    ITextRanges ranges(rangesRef);
    if (ranges.GetSize() > 0)
         ITextRange range = ranges.Item(0);
         ICharFeatures features = range.GetUniqueLocalCharFeatures();
         IFont  font;                     // I don't see any method to put desired font.
       // features.SetFont(); 
    Thanks.
    D.A

    First, get the font:
    AIFontKey fontKey = 0;
    AIErr error = sAIFont->FindFont("Times New Roman Regular", kAIAnyFontTechnology, kNativeAIScript, 0, &fontKey);
    // do something with error
    ATE::FontRef fontRef = 0;
    error = sAIFont->FontFromFontKey(fontKey, &fontRef);
    // do something with error
    ATE::IFont font(fontRef);
    Then, apply it like this:
    ATE::TextRangeRef textRangeRef = 0;
    AIErr error = sAITextFrame->GetATETextRange(handle_to_artwork, &textRangeRef);
    // check error
    ATE::ITextRange textRange(textRangeRef);
    ATE::ICharFeatures charFeatures = textRange.GetUniqueLocalCharFeatures();
    charFeatures.SetFont(font);
    textRange.ReplaceOrAddLocalCharFeatures(charFeatures);
    There are a few other ways to set the text, but you need to understand how character & paragraph styles interact with each other to understand the differneces. This is the most straight forward way to do it though.

  • Adobe Acrobat. Change "Copy selected text into Highlight, Cross-Out, ..." also for highlights made before changing the setting

    I am looking for a solution to apply the "Copy selected text into Highlight, Cross-Out, and Underline comment pop-ups" setting to highlights that I made before I changed this setting.
    Someone wrote a batch for this which costs 60 dollar and this seems to do what I am looking for: Custom-made Adobe Scripts: Acrobat -- Retroactively Copy Highlighted Text into Comments
    Where can I find Adobe's solution for this problem?  I do not want to buy external batches for a professional software suit.
    I expect that this is a common problem for people who start to organize a large literature base with many pdfs and must keep track of highlighted text. I was not previously aware of the "Copy selected..."setting, but I need to change it now for all my pdf files to make them compatible with a reference manager that I want to use. New comments are now compatible, but the hundreds(!) of pdfs that I worked through before are not, so copy pasting the highlighted text into comments is not an option.

    Hi gb145,
    You are posting on acrobat.com online service forums.
    Kindly post this query in Acrobat forums:Acrobat
    Regards,
    Florence

  • JTextPane, Selecting Text and Applying Styles

    Hello,
    Anyone encounter this situation? I have a mini word processor application that I have written using the RTFEditor kit and a JTextPane. To change style, e.g bold, font size, font face, etc, one can select text and then click a button or select a menu item. That part works fine. The styles are primarily changed by using the Action classes provided in the javax.swing.text.* package.
    The problem is, that if a user selected text of more than one style, all of the text is automatically converted to the style of the first part of the text selected, without the user even eanting to change ANY style just yet.
    If anyone knows why this might be happening I would surely appreciate it.
    Thanks,
    acal

    Solution to the style appling problem...
    public void actionPerformed( ActionEvent e )
            if (flag) return;
            if(e.getSource() == boldButton)
                SimpleAttributeSet attrs = new SimpleAttributeSet();
                attrs.addAttribute(StyleConstants.Bold,boldButton.isSelected());
                applyStyleToSelection(attrs);
                editorPane.grabFocus();
                return;
    public void applyStyleToSelection(AttributeSet attrs)
            int start = editorPane.getSelectionStart();
            int end = editorPane.getSelectionEnd();
            DefaultStyledDocument doc = (DefaultStyledDocument) editorPane.getDocument();
            doc.setCharacterAttributes(start, end - start, attrs, false);
            StyledEditorKit styled = (StyledEditorKit) editorPane.getEditorKit();
            MutableAttributeSet mas = styled.getInputAttributes();
            mas.addAttributes(attrs);
        }Filipi Silveira
    [email protected]

Maybe you are looking for