Page 2 of 2 FirstFirst 12
Results 21 to 34 of 34
  1. #21
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,009
    Rep Power
    6

    Default Re: To highlight or not to highlight that is the question?

    Quote Originally Posted by willemjav View Post
    camickr, I am impressed, you really do know some swing-magic: wow!
    Java Tips Weblog

    Why yes, yes he does :)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  2. #22
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    when I change extends AbstractAction for TextAction* I get an error saying:
    "cannot find symbol constructor TextAction()"


    Java Code:
    class TextHighlightAction extends AbstractAction {
            private final String colorstring;
            public TextHighlightAction(String colorstring) {
                this.colorstring = colorstring;
                 
            }
    
            public void actionPerformed(ActionEvent ae) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        }
    *TextAction has no default constructor?!

    and this is not what we are looking for:
    http://www.cs.cmu.edu/~rcm/websphinx...ghtAction.html
    Last edited by willemjav; 03-21-2014 at 06:01 PM.

  3. #23
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    So I go with thew AbstractAction instead?
    and I do know what I should be doing:
    1) make an object for each highlight color
    2) set the name property for the color
    3) add to the combo
    4) and render the object in getting the name for the combo item display
    etc.

    ps not sure what to do with getSelectionStart/End()
    but when I add this somehow to the code:
    int selectionStart = textpane.getSelectionStart();
    int selectionEnd = textpane.getSelectionEnd();
    it may work out, right?
    Last edited by willemjav; 03-21-2014 at 06:12 PM.

  4. #24
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    I need a hand, I have it almost going, but have some trouble with the renderer (of course)
    see line 82!

    Java Code:
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    
    /**
     *
     * @author willem
     */
    
    public class HighlightTest {
        private JTextPane textpane;
        private LinkedHashMap <String, Color> colorMap;
      
        public HighlightTest() {
    
            StyledDocument doc = new DefaultStyledDocument();
            textpane = new JTextPane();
            textpane.setDocument(doc);
            colorMap = getColorList();
            // From _One Hundred Years of Solitude_ by Gabriel Garcia Marquez.
            String s = "Jos\u00e9 Arcadio Buend\u00eda spent the long months " +
               "of the rainy season shut up in a small room that he " +
               "had built in the rear of the house so that no one " +
               "would disturb his experiments. Having completely abandoned " +
               "his domestic obligations, he spent entire nights in the " +
               "courtyard watching the course of the stars and he almost " +
               "contracted sunstroke from trying to establish an exact method " +
               "to ascertain noon.";
            textpane.setText(s);
        }
    
        public static void main(String[] arg) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("HighlightTest");
            frame.setBounds(100, 30, 600, 400);
            HighlightTest  highlighttest = new HighlightTest();
            Container c = frame.getContentPane();
            c.add(highlighttest.doGUI());
            frame.setVisible(true);
        }
    
        public JPanel doGUI() {
            JPanel jp = new JPanel(new BorderLayout());
            JScrollPane spane = new JScrollPane(textpane);
            spane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            spane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            spane.setPreferredSize(new Dimension(780, 830));
            jp.add(spane, BorderLayout.CENTER);
            jp.add(doColorCombo(), BorderLayout.NORTH);
            return jp;
        }
    
        public JComboBox doColorCombo() {
            Set entries = colorMap.entrySet();
            Iterator iter = entries.iterator();
            Map.Entry entry;
            String key;
            Color value;
            Action[] actions = new Action[colorMap.size()];
            int count = 0;
            while (iter.hasNext()) {
                entry = (Map.Entry)iter.next();
                key = (String) entry.getKey();
                value = (Color) entry.getValue();
                Action ac = new TextHighlightAction(key, value);
                actions[count] = ac;
                count++;
            }
    
    
            final JComboBox combo = new JComboBox(actions); //combo.setName("fontsize");
            combo.setRenderer(new ComboRenderer());
            
            combo.addActionListener(new ActionListener()  {
                public void actionPerformed(ActionEvent event) {         
                  Action action = (Action) combo.getSelectedItem();
                  action.actionPerformed( null );
                }
            });
           
            return combo;
        }
    
        class TextHighlightAction extends AbstractAction {
            private String colorString = "";
            private Color color;
            public TextHighlightAction(String colorString, Color color) {
                this.colorString = colorString;
                this.color = color;
            }
    
            public void actionPerformed(ActionEvent ae) {
               
                {	// "Constructor"
                    putValue(NAME, colorString);
                    putValue(SMALL_ICON, null);
                    putValue(MNEMONIC_KEY, new Integer('N'));
                    putValue(SHORT_DESCRIPTION, "Creates a whatever");
                    putValue(LONG_DESCRIPTION, "Creating new whatever...");
                }
                try {
                    int selectionStart = textpane.getSelectionStart();
                    int selectionEnd = textpane.getSelectionEnd();
                    DefaultHighlighter.DefaultHighlightPainter p =
                    new DefaultHighlighter.DefaultHighlightPainter(color);
                    DefaultHighlighter highlighter =
                                     (DefaultHighlighter) textpane.getHighlighter();
                    highlighter.setDrawsLayeredHighlights(false);
                //  DefaultHighlighter actualHighlight =   (DefaultHighlighter)
                           highlighter.addHighlight(selectionStart, selectionEnd, p);
                } catch (BadLocationException ex) {
                    System.err.println("bad location: " + ex);
                }
            }
        }
    
        public LinkedHashMap getColorList() {
             colorMap = new LinkedHashMap<String, Color>();
             colorMap.put("Red", Color.red);
             colorMap.put("Green", Color.green);
             colorMap.put("Blue", Color.blue);
             colorMap.put("Yellow", Color.yellow);
             colorMap.put("White", Color.white);
             colorMap.put("Orange", Color.orange);
             return colorMap;
        }
    
        private class ComboRenderer extends DefaultListCellRenderer {
                @Override
                public Component getListCellRendererComponent(JList list,
                        Object value, int index, boolean isSelected,
                                                    boolean cellHasFocus) {
                    JLabel result = (JLabel)
                    super.getListCellRendererComponent(list, value, index,
                                                    isSelected, cellHasFocus);
                    final Object colorObj = value;
                    Action action = null;
                    action = (Action) colorObj;
                    String s = (String) action.getValue(Action.NAME);
                    Font font = new Font("times", Font.PLAIN, 16);
                    result.setFont(font);
                    result.setText(s);
                    return this;
                }
         }
    
    
    }

  5. #25
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    Got it!

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    
    /**
     *
     * @author willem
     */
    
    public class HighlightTest {
        private JTextPane textpane;
        private LinkedHashMap <String, Color> colorMap;
      
        public HighlightTest() {
    
            StyledDocument doc = new DefaultStyledDocument();
            textpane = new JTextPane();
            textpane.setDocument(doc);
            colorMap = getColorList();
            // From _One Hundred Years of Solitude_ by Gabriel Garcia Marquez.
            String s = "Jos\u00e9 Arcadio Buend\u00eda spent the long months " +
               "of the rainy season shut up in a small room that he " +
               "had built in the rear of the house so that no one " +
               "would disturb his experiments. Having completely abandoned " +
               "his domestic obligations, he spent entire nights in the " +
               "courtyard watching the course of the stars and he almost " +
               "contracted sunstroke from trying to establish an exact method " +
               "to ascertain noon.";
            textpane.setText(s);
        }
    
        public static void main(String[] arg) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("HighlightTest");
            frame.setBounds(100, 30, 600, 400);
            HighlightTest  highlighttest = new HighlightTest();
            Container c = frame.getContentPane();
            c.add(highlighttest.doGUI());
            frame.setVisible(true);
        }
    
        public JPanel doGUI() {
            JPanel jp = new JPanel(new BorderLayout());
            JScrollPane spane = new JScrollPane(textpane);
            spane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            spane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            spane.setPreferredSize(new Dimension(780, 830));
            jp.add(spane, BorderLayout.CENTER);
            jp.add(doColorCombo(), BorderLayout.NORTH);
            return jp;
        }
    
        public JComboBox doColorCombo() {
            Set entries = colorMap.entrySet();
            Iterator iter = entries.iterator();
            Map.Entry entry;
            String key;
            Color value;
            Action[] actions = new Action[colorMap.size()];
            int count = 0;
            while (iter.hasNext()) {
                entry = (Map.Entry)iter.next();
                key = (String) entry.getKey();
                value = (Color) entry.getValue();
                Action ac = new TextHighlightAction(key, value);
                actions[count] = ac;
                count++;
            }
    
    
            final JComboBox combo = new JComboBox(actions); //combo.setName("fontsize");
            combo.setRenderer(new ComboRenderer());
            
            combo.addActionListener(new ActionListener()  {
                public void actionPerformed(ActionEvent event) {         
                  Action action = (Action) combo.getSelectedItem();
                  action.actionPerformed( null );
                }
            });
           
            return combo;
        }
    
        class TextHighlightAction extends AbstractAction {
            private String colorString = "";
            private Color color;
    
            public TextHighlightAction(String colorString, Color color) {
                this.colorString = colorString;
                this.color = color;
                this.putValue(Action.NAME, colorString);
                this.putValue(Action.SMALL_ICON, new ColorFillIcon(color, 15, 10, 1));
            }
    
            public void actionPerformed(ActionEvent ae) {
                try {
                    int selectionStart = textpane.getSelectionStart();
                    int selectionEnd = textpane.getSelectionEnd();
                    DefaultHighlighter.DefaultHighlightPainter p =
                    new DefaultHighlighter.DefaultHighlightPainter(color);
                    DefaultHighlighter highlighter =
                                     (DefaultHighlighter) textpane.getHighlighter();
                    highlighter.setDrawsLayeredHighlights(false);
                //  DefaultHighlighter actualHighlight =   (DefaultHighlighter)
                           highlighter.addHighlight(selectionStart, selectionEnd, p);
                } catch (BadLocationException ex) {
                    System.err.println("bad location: " + ex);
                }
            }
        }
    
        public LinkedHashMap getColorList() {
             colorMap = new LinkedHashMap<String, Color>();
             colorMap.put("Red", Color.red);
             colorMap.put("Green", Color.green);
             colorMap.put("Blue", Color.blue);
             colorMap.put("Yellow", Color.yellow);
             colorMap.put("Orange", Color.orange);
             colorMap.put("White", Color.white);
             return colorMap;
        }
    
        private class ComboRenderer extends DefaultListCellRenderer {
                @Override
                public Component getListCellRendererComponent(JList list,
                        Object value, int index, boolean isSelected,
                                                    boolean cellHasFocus) {
                    JLabel result = (JLabel) super.getListCellRendererComponent(list,
                                        value, index, isSelected, cellHasFocus);
                    final Object colorObj = value;
                    Action action = null;
                    action = (Action) colorObj;
                    String s = (String) action.getValue(Action.NAME);
                    Font font = new Font("times", Font.PLAIN, 16);
                    setFont(font);
                    setText(s);
                    return this;
                }
         }
    
    
    }
    Last edited by willemjav; 03-21-2014 at 10:17 PM.

  6. #26
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: To highlight or not to highlight that is the question?

    Good stuff, however I still have several comments:

    Java Code:
    StyledDocument doc = new DefaultStyledDocument();
    textpane = new JTextPane();
    textpane.setDocument(doc);
    Why are you creating a Document? JTextPane does this for you. If you think you need a reference to the Document, then use the getSyledDocument() method of JTextPane.

    *TextAction has no default constructor?!
    When you extend TextAction you need to invoke:

    Java Code:
    super(colorString);
    as the first statement in the constructor

    Now that you are extending TextAction, you can use the getFocusedComponent() method to get the actual text pane where you want to highlight text. An Action should NOT reference an instance variable of your class. The Action should be able to work on any text component in the frame.

    Java Code:
    highlighter.setDrawsLayeredHighlights(false);
    Why do you keep setting this property of the highlighter in the actionPerformed() method? I believe I suggested this should be done once when you create the JTextPane.

    Java Code:
    Font font = new Font("times", Font.PLAIN, 16);
    The font object should be created in the constructor of the class, not in the rendering code.

    Good luck.
    Last edited by camickr; 03-22-2014 at 02:57 AM.

  7. #27
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    I highly appreciate your remarks and you are right one by one (I am cutting with an axe but you are seeing the splinters).
    That is the way to go that get it ALL RIGHT!
    Thanks!
    (I am also reading ones again Java in a Nutshell, so I am working seriously to get all the "details" right)

  8. #28
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    There is still one more interesting thing to tackle though!
    I am using already for some weeks the next generic (that is what you say, right?)
    class to see what is inside a text component (how all the data gets internal presented by the Doc).
    The next class (simply initiate it and call the method showModel(StyledDocument doc)
    really helped me a lot to see what is going on!

    Now the point I am making is when doing all actions like "StyledEditorKit.FontFamilyAction":

    Java Code:
    actionmap.put(fontname, new StyledEditorKit.FontFamilyAction(fontname, fontname));
    action = actionmap.get(fontname);
    action.putValue(Action.NAME, fontname);
    and for style:
    Java Code:
    action = actionmap.get(fontStyleList[i].getFontStyleKey()); //font-bold, font-italic, font-underline
    action.putValue(Action.NAME, fontStyleList[i].getFontStyleName()); // Bold, Italic, Underlined
    action.putValue(Action.SMALL_ICON, iconImport.getImageIcon(fontStyleList[i].getFontStyleIcon())); // a saved image of that style
    for size:
    Java Code:
    actionmap.put("font-size-" + fsize, new StyledEditorKit.FontSizeAction("font-size-" + fsize, Integer.parseInt(fsize)));
    Action action = actionmap.get("font-size-" + fsize);
    action.putValue(Action.NAME, fsize);
    for color:
    Java Code:
    actionmap.put("font-color-" + key, new StyledEditorKit.ForegroundAction("font-color-" + key, value)); 
    action = actionmap.get("font-color-" + key); // key like "Black", value like Color.black
    action.putValue(Action.NAME, key);
    action.putValue(Action.SMALL_ICON, new ColorFillIcon(value, 15, 10, 1))
    I find them all back when viewing the model (very interesting)!
    But unfortunately I can not get my newly added highlights to appear at that model view!

    So how to make that work?




    Java Code:
    import javax.swing.text.*;
    import java.io.*;
    import java.util.*;
    
    public class ModelDisplay {
        private static final int CONTENT_COLUMNS = 40;
        private static int paragraphCount;
        private static int childcount;
        public static String showModel(StyledDocument doc) {
            StringWriter sw = new StringWriter();
            BufferedWriter w = new BufferedWriter(sw);
            try {
                w.write("Document contains " + doc.getLength() + " characters\n");
                // Get the root element and display it.
                // We also display any elements that this
                // element contains
                Element root = doc.getDefaultRootElement();
                paragraphCount = 0;
                w.write(" There are " + root.getElementCount() + " paragraphs\n\n");
                showElement(root, w, 0);
                w.flush();
                return sw.toString();
            } catch (IOException e) {
                return "I/O Exception";
            } catch (BadLocationException e) {
                return "Bad location exception";
            }
        }
    
        protected static void showElement(Element e, Writer w, int indent)
                                    throws IOException, BadLocationException {
            // Show the element name first
            String name = e.getName();
            int startOffset = e.getStartOffset();
            int endOffset = e.getEndOffset();
            AttributeSet a = e.getAttributes();
            int attrs = a.getAttributeCount();
            int childrennumber = e.getElementCount();
            int count = 0;
    
            doIndent(w, indent);
            w.write("[ " + name);
            //
    
            if (name.equals(AbstractDocument.SectionElementName)) {
                 w.write("  ], start offset: " + startOffset +
                                                   ", end: " + endOffset + "\n");
            }
    
            if (name.equals(AbstractDocument.ParagraphElementName)) {
                 w.write(" " + paragraphCount + " ], start offset: " + startOffset +
                                                    ", end: " + endOffset + "\n");
                  paragraphCount++;
            }
    
            if (name.equals(AbstractDocument.ContentElementName)) {
                 w.write(" " + childcount + " ], start offset: "
                                      + startOffset + ", end: " + endOffset + "\n");
            }
            
            // Display the attributes, if there are any...
            if (attrs == 0) {
                doIndent(w, indent + 2);
                w.write("{ No attributes }\n");
            } else {  
                Enumeration enumr = a.getAttributeNames();
                while (enumr.hasMoreElements()) {
                    Object o = enumr.nextElement();
                    String ename = o.toString();
                    doIndent(w, indent + 2);
                    w.write("{ " + count + " " + ename + " = ");
                    String value = a.getAttribute(o).toString();
                    w.write(value + " }\n");
                    count++;
                }
            }
    
            // If it is content, show some of the data
            if (name.equals(AbstractDocument.ContentElementName)) {
                // Display no more than CONTENT_COLUMNS characters
                int length = endOffset - startOffset;
                if (length > CONTENT_COLUMNS) {
                    length = CONTENT_COLUMNS;
                }
                if (length > 0) {
                    Segment s = new Segment();
                    e.getDocument().getText(startOffset, length, s);
                    doIndent(w, indent + 8);
                    for (int i = 0; i < length; i++) {
                        char c = s.array[i + s.offset];
                        if (c == '\n') {
                            w.write(" \n ");
                        } else if (c == '\r') {
                            w.write(" \r ");
                        } else {
                            w.write(s.array[i + s.offset]);
                        }
                    }
                } w.write("\n");
            }
            w.write("\n");
    
            // Now traverse the children of this element  
            for (int i = 0; i < childrennumber; i++) {
                childcount = i;
                showElement(e.getElement(i), w, indent + 4);
            }
        }
    
        // Indent by the given amount
        protected static void doIndent(Writer w, int n)
        throws IOException {
            for (int i = 0; i < n; i++) {
                w.write(" ");
            }
        }
    }
    Last edited by willemjav; 03-22-2014 at 03:36 PM.

  9. #29
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    Maybe I am seeing this wrong?
    When looking into StyleConstants, it has four inner classes and one of them is ColorConstants.
    But there is also the method get/setBackground, which concerns the color.
    The setForeGround sets the font/text color, right!
    Could the getBackground(AttributeSet a) work out for the highlighter?

    Man, this stuff is really confusing and it is hard to find textbooks that explain
    this material well!
    Last edited by willemjav; 03-23-2014 at 12:04 AM.

  10. #30
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    Rethinking it all (once again) I believe that the highlight should not be stored into
    the text attributes and threaded apart from font size, color etc. Right?

    Find the improved and remodeled highlight code at the bottom of this post.
    camickr will notice that I haven't yet implemented getFocusedComponent(), because I do not know
    how, but I'll find that out soon!

    First, I have changed the text pane into a text area and I have implemented the document view mentioned in post 28;
    Secondly, I added a new action and a menu-item to print that model (see last menu item);
    Thirdly, I added two line-breaks (\n) to the text to appear at the text component.

    VERY IMPORTANT PLEASE CHANGE THE ARG TYPE OF showModel FROM StyledDocument into Document!
    Now when NOT adding any highlights and printing the model this will show up:

    Document contains 397 characters
    There are 3 paragraphs //[? my comment]

    [ paragraph 0 ], start offset: 0, end: 398
    { No attributes }

    [ content 0 ], start offset: 0, end: 176
    { No attributes }
    José Arcadio Buendía spent the long mont

    [ content 1 ], start offset: 176, end: 230
    { No attributes }
    Having completely abandoned his domestic

    [ content 2 ], start offset: 230, end: 398
    { No attributes }
    he spent entire nights in the courtyard

    After adding some highlights the model is actually the same!

    Now I changed the JTextArea into the JTextPane (see code) and the printed model shows now:

    Document contains 397 characters
    There are 3 paragraphs

    [ section ], start offset: 0, end: 398
    { No attributes }

    [ paragraph 0 ], start offset: 0, end: 176
    { 0 resolver = NamedStyle:default {name=default,size=13,italic=false,bold=false,FONT _ATTRIBUTE_KEY=com.apple.laf.AquaFonts$DerivedUIRe sourceFont[family=Lucida Grande,name=Lucida Grande,style=plain,size=13],family=Lucida Grande,} }

    [ content 0 ], start offset: 0, end: 176
    { No attributes }
    José Arcadio Buendía spent the long mont

    [ paragraph 1 ], start offset: 176, end: 230
    { 0 resolver = NamedStyle:default {name=default,size=13,italic=false,bold=false,FONT _ATTRIBUTE_KEY=com.apple.laf.AquaFonts$DerivedUIRe sourceFont[family=Lucida Grande,name=Lucida Grande,style=plain,size=13],family=Lucida Grande,} }

    [ content 0 ], start offset: 176, end: 230
    { No attributes }
    Having completely abandoned his domestic

    [ paragraph 2 ], start offset: 230, end: 398
    { 0 resolver = NamedStyle:default {name=default,size=13,italic=false,bold=false,FONT _ATTRIBUTE_KEY=com.apple.laf.AquaFonts$DerivedUIRe sourceFont[family=Lucida Grande,name=Lucida Grande,style=plain,size=13],family=Lucida Grande,} }

    [ content 0 ], start offset: 230, end: 398
    { No attributes }
    he spent entire nights in the courtyard

    Again after adding some highlight no change when printing the model



    Of course one could add some of the font actions mentioned in post 28
    and the model would look like this:

    Document contains 397 characters
    There are 3 paragraphs

    [ section ], start offset: 0, end: 398
    { No attributes }

    [ paragraph 0 ], start offset: 0, end: 176
    { 0 resolver = NamedStyle:default {name=default,italic=false,bold=false,FONT_ATTRIBU TE_KEY=com.apple.laf.AquaFonts$DerivedUIResourceFo nt[family=Lucida Grande,name=Lucida Grande,style=plain,size=13],family=Lucida Grande,size=13,} }

    [ content 0 ], start offset: 0, end: 175
    { 0 foreground = java.awt.Color[r=255,g=0,b=0] }
    { 1 family = Adobe Arabic }
    { 2 size = 24 }
    José Arcadio Buendía spent the long mont

    [ content 1 ], start offset: 175, end: 176
    { No attributes }



    [ paragraph 1 ], start offset: 176, end: 230
    { 0 resolver = NamedStyle:default {name=default,italic=false,bold=false,FONT_ATTRIBU TE_KEY=com.apple.laf.AquaFonts$DerivedUIResourceFo nt[family=Lucida Grande,name=Lucida Grande,style=plain,size=13],family=Lucida Grande,size=13,} }

    [ content 0 ], start offset: 176, end: 229
    { 0 italic = true }
    { 1 bold = true }
    { 2 family = Adobe Hebrew }
    { 3 size = 16 }
    Having completely abandoned his domestic

    [ content 1 ], start offset: 229, end: 230
    { No attributes }



    [ paragraph 2 ], start offset: 230, end: 398
    { 0 resolver = NamedStyle:default {name=default,italic=false,bold=false,FONT_ATTRIBU TE_KEY=com.apple.laf.AquaFonts$DerivedUIResourceFo nt[family=Lucida Grande,name=Lucida Grande,style=plain,size=13],family=Lucida Grande,size=13,} }

    [ content 0 ], start offset: 230, end: 233
    { 0 underline = false }
    { 1 foreground = java.awt.Color[r=0,g=0,b=255] }
    { 2 family = Al Bayan }
    { 3 size = 36 }
    he

    [ content 1 ], start offset: 233, end: 238
    { 0 underline = true }
    { 1 foreground = java.awt.Color[r=0,g=0,b=255] }
    { 2 family = Al Bayan }
    { 3 size = 36 }
    spent

    [ content 2 ], start offset: 238, end: 297
    { 0 underline = false }
    { 1 foreground = java.awt.Color[r=0,g=0,b=255] }
    { 2 family = Al Bayan }
    { 3 size = 36 }
    entire nights in the courtyard watching

    [ content 3 ], start offset: 297, end: 302
    { 0 underline = true }
    { 1 foreground = java.awt.Color[r=0,g=0,b=255] }
    { 2 family = Al Bayan }
    { 3 size = 36 }
    stars

    [ content 4 ], start offset: 302, end: 397
    { 0 underline = false }
    { 1 foreground = java.awt.Color[r=0,g=0,b=255] }
    { 2 family = Al Bayan }
    { 3 size = 36 }
    and he almost contracted sunstroke from

    [ content 5 ], start offset: 397, end: 398
    { No attributes }



    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    /**
     * @author willem
     */
    public class HighlightTest {
        private JTextPane textpane; // change into JTextPane
        private LinkedHashMap <String, Color> colorMap;
        private Font font;
        private DefaultHighlighter highlighter;
        private ModelDisplay md;
        
      
        public HighlightTest() {
            textpane = new JTextPane(); // change into JTextPane
         //   textpane.setLineWrap(true); // when text pane tkae this out
          //  textpane.setWrapStyleWord(true); // idem
            md = new ModelDisplay();
            colorMap = getColorList();
            font = new Font("times", Font.PLAIN, 14);
            highlighter = (DefaultHighlighter) textpane.getHighlighter();
            highlighter.setDrawsLayeredHighlights(false);
            // From _One Hundred Years of Solitude_ by Gabriel Garcia Marquez.
            String s = "Jos\u00e9 Arcadio Buend\u00eda spent the long months " +
               "of the rainy season shut up in a small room that he " +
               "had built in the rear of the house so that no one " +
               "would disturb his experiments.\nHaving completely abandoned " +
               "his domestic obligations,\nhe spent entire nights in the " +
               "courtyard watching the course of the stars and he almost " +
               "contracted sunstroke from trying to establish an exact method " +
               "to ascertain noon.";
            textpane.setText(s);
        }
    
        public static void main(String[] arg) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("HighlightTest");
            frame.setBounds(100, 30, 600, 400);
            HighlightTest  highlighttest = new HighlightTest();
            Container c = frame.getContentPane();
            c.add(highlighttest.doGUI());
            frame.setVisible(true);
        }
    
        public JPanel doGUI() {
            JPanel jp = new JPanel(new BorderLayout());
            JScrollPane spane = new JScrollPane(textpane);
            spane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            spane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            spane.setPreferredSize(new Dimension(780, 830));
            jp.add(spane, BorderLayout.CENTER);
            jp.add(doColorCombo(), BorderLayout.NORTH);
            return jp;
        }
    
        public JComboBox doColorCombo() {
            Set entries = colorMap.entrySet();
            Iterator iter = entries.iterator();
            Map.Entry entry;
            String key;
            Color value;
            Action[] actions = new Action[colorMap.size()];
            int count = 0;
            while (iter.hasNext()) {
                entry = (Map.Entry)iter.next();
                key = (String) entry.getKey();
                value = (Color) entry.getValue();
                Action ac = new TextHighlightAction(key, value);
                actions[count] = ac;
                count++;
            }
            final JComboBox combo = new JComboBox(actions); //combo.setName("fontsize");
            combo.addItem(new ModelDispalyAction());
            combo.setRenderer(new ComboRenderer());
            combo.addActionListener(new ActionListener()  {
                public void actionPerformed(ActionEvent event) {         
                  Action action = (Action) combo.getSelectedItem();
                  action.actionPerformed( null );
                }
            });
            return combo;
        }
    
        class ModelDispalyAction extends AbstractAction {
            public ModelDispalyAction() {
                this.putValue(Action.NAME, "showmodel");
            }
            public void actionPerformed(ActionEvent ae) {
                System.out.println(md.showModel(textpane.getDocument()));
            }
    
        }
    
        class TextHighlightAction extends TextAction {
            private String colorString = "";
            private Color color;
    
            public TextHighlightAction(String colorString, Color color) {
                super(colorString);
                this.colorString = colorString;
                this.color = color;
                this.putValue(Action.NAME, colorString);
                this.putValue(Action.SMALL_ICON, new ColorFillIcon(color, 15, 10, 1));
            }
    
            public void actionPerformed(ActionEvent ae) {
                try {
                    int selectionStart = textpane.getSelectionStart();
                    int selectionEnd = textpane.getSelectionEnd();
                    DefaultHighlighter.DefaultHighlightPainter p =
                    new DefaultHighlighter.DefaultHighlightPainter(color);
                //  DefaultHighlighter actualHighlight =   (DefaultHighlighter)
                           highlighter.addHighlight(selectionStart, selectionEnd, p);
                } catch (BadLocationException ex) {
                    System.err.println("bad location: " + ex);
                }
            }
        }
    
        public LinkedHashMap getColorList() {
             colorMap = new LinkedHashMap<String, Color>();
             colorMap.put("Red", Color.red);
             colorMap.put("Green", Color.green);
             colorMap.put("Blue", Color.blue);
             colorMap.put("Yellow", Color.yellow);
             colorMap.put("Orange", Color.orange);
             colorMap.put("White", Color.white);
             return colorMap;
        }
    
        private class ComboRenderer extends DefaultListCellRenderer {
                @Override
                public Component getListCellRendererComponent(JList list,
                        Object value, int index, boolean isSelected,
                                                    boolean cellHasFocus) {
                    JLabel result = (JLabel) super.getListCellRendererComponent(list,
                                        value, index, isSelected, cellHasFocus);
                    final Object colorObj = value;
                    Action action = null;
                    action = (Action) colorObj;
                    String s = (String) action.getValue(Action.NAME);
                    setFont(font);
                    setText(s);
                    return this;
                }
         }
    }

  11. #31
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    One tends to focus on the computer screen, but the actual screen stuff gets "saved" into the model.
    So the action in relation to the fonts (family, size etc) are saved into a tree of attributes etc, good!
    The highlights are kept apart and are available through:

    Java Code:
    class HighlightDisplayAction extends AbstractAction {
            public HighlightDisplayAction() {
                this.putValue(Action.NAME, "displayAllHighlights");
            }
            public void actionPerformed(ActionEvent ae) {
                Highlight[] highlights = highlighter.getHighlights();
                for (int i=0; i < highlights.length; i++) {
                    int startOffset = highlights[i].getStartOffset();
                    int endOffset = highlights[i].getEndOffset();
                    HighlightPainter painter = highlights[i].getPainter();
                    // painter. could I get the color of the highlight as well
                    System.out.println(i + " highlight start: " + startOffset 
                                                           + " end " + endOffset);
                }
            }
    
        }

    That would be the end to the highlight story, what you think camickr?

    ps this action could be added finally to the combo as well.....
    Last edited by willemjav; 03-23-2014 at 12:34 PM.

  12. #32
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    what is mend by this:
    "An Action should NOT reference an instance variable of your class. The Action should be able to work on any text component in the frame."
    I do not understand this could you elaborate a little more or give an example?

  13. #33
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: To highlight or not to highlight that is the question?

    I do not understand this could you elaborate a little more or give an example?
    In the first code example for creating the ActionListener of your combo box you used:

    Java Code:
    public void actionPerformed(ActionEvent event) {
        Object sc = event.getSource();
        JComboBox combo = (JComboBox) sc;
    This is good because you get the combo box reference from the ActionEvent. This means the the ActionListener could potentially be used on any combo box in any application that requires that functionality. This is how you write reusable code.

    In your last example when you created the HighlightAction you used:

    Java Code:
    final JComboBox combo = new JComboBox(actions); 
             
    combo.addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent event) {         
            Action action = (Action) combo.getSelectedItem();
    This is not good because you are referencing a local variable and you had to make it final so it would compile. This is not really a big deal because you are using an anonymous inner class so it can never be reused in another application, but there is no reason you shouldn't get the combo box reference from the ActionEvent.

    Actions on the other hand are meant to be reusable. The Actions from the editor kit will work on any text component in any application. The Action can be invoked from a JButton or JMenuItem so the source of the event is that component, not the text component that you want to Action to be performed on. What if you had two text panes on your GUI? How would your code work? If wouldn't because you are hardcoding the reference to the text pane inside the Action. You should never do that.

    So how to you get a reference to the text component? As I suggested earlier, the TextAction provides a getFocusedComponent() method that will return the last focused text component. You use this method to get the reference to the text pane.

    You can always look at the source code of the StyledEditorKit to see what the code for the default Actions looks like.

    Regarding your other questions, I don't know the internals of how attributes work. I'm not sure why the foreground color would be an attribute but background color isn't. This thread is getting too involved. I would suggest you post questions in a new thread.

  14. #34
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: To highlight or not to highlight that is the question?

    I got it, thanks, camickr!
    I am preparing indeed a new thread which will name:
    "Copying with Flavors"
    For the moment I am looking into the class TransferHandler and interface Transferable.
    For the moment I am advancing......

Page 2 of 2 FirstFirst 12

Similar Threads

  1. Highlight every third line.
    By Reptyle216 in forum New To Java
    Replies: 22
    Last Post: 11-05-2013, 12:35 AM
  2. GNU Source-highlight 3.1.6
    By java software in forum Java Software
    Replies: 0
    Last Post: 01-01-2012, 12:58 PM
  3. highlight content
    By Saran185 in forum NetBeans
    Replies: 1
    Last Post: 01-31-2011, 10:25 AM
  4. highlight text
    By Saran185 in forum AWT / Swing
    Replies: 2
    Last Post: 01-28-2011, 03:24 PM
  5. Date highlight
    By Shyamz1 in forum New To Java
    Replies: 8
    Last Post: 11-26-2010, 02:19 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •