Page 1 of 2 12 LastLast
Results 1 to 20 of 34
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

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

    Find here a small sample program that adds an highlight to a text pane.
    The combo makes you choose the highlight color.

    Everything goes as planned: great!

    But what happens when you changed your mind and want to get rid of some, or all highlights?
    When selecting the last two combo items you can get rid of the last added or even all highlights: good!

    If one would save highlight-references into an array or list, one could take them out one by one, right!

    But when having a text application in mind that last suggestion is not very use full!

    So how to get rid of highlights by using the mouse?
    The first problem you're facing is that you cannot even selected OVER a planted highlight!

    You might be able to save the present highlights into a list together with the highlight start-and-end-offsets,
    and figure out somehow when the mouse is going over that area, right?

    But wait a moment, adding highlights happen in the "view" domain, right?
    So what would be the format of adding highlights to the "model" domain?

    We might have to go into this direction?

    Java Code:
    attrstr.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
                     InputMethodHighlight.SELECTED_CONVERTED_TEXT_HIGHLIGHT,
                     0, str.length());
    Who cab help me out and "highlight" some of these tricky questions.........


    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.*;
    
    /**
     *
     * @author willem
     */
    
    public class HighlightTest {
        private JTextPane textpane;
        private int dot, mark;
        private LinkedHashMap <String, Color> colorMap;
        private Object actualHighlight;
        private Highlighter highligter;
    
        public HighlightTest() {
            StyledDocument doc = new DefaultStyledDocument();
            textpane = new JTextPane();
            textpane.setDocument(doc);
            textpane.addCaretListener(new CaretListener() {
                public void caretUpdate(CaretEvent e) {
                    dot = e.getDot();
                    mark = e.getMark();
                }
             });
    
            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 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() {
            String[] colorlist = {"Red", "Blue", "Yellow", "Green", "White", "Last", "All"};
            final JComboBox combo = new JComboBox(colorlist); //combo.setName("fontsize");
            combo.setSize(200, combo.getPreferredSize().height);
            combo.addActionListener(new ActionListener()  {
                public void actionPerformed(ActionEvent event) {
                    Object sc = event.getSource();
                    Set entries = colorMap.entrySet();
                    Iterator iter = entries.iterator();
                    JComboBox combo = (JComboBox) sc;
                    String comboitem = (String) combo.getSelectedItem();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry)iter.next();
                        String key = (String) entry.getKey();
                        Color value = (Color) entry.getValue();
                        if (comboitem.equals("All")) { // take out all higlights
                            highligter.removeAllHighlights();
                        }
                         if (comboitem.equals("Last")) { //take out last highlight
                            highligter.removeHighlight(actualHighlight);
                        }
                        if (comboitem.equals(key)) {
                            try {
    
                                DefaultHighlighter.DefaultHighlightPainter p =
                            new DefaultHighlighter.DefaultHighlightPainter(value);
                                highligter = textpane.getHighlighter();
                                actualHighlight = highligter.addHighlight(mark, dot, p);
                            } catch (BadLocationException ex) {
                                System.err.println("bad location: " + ex);
                            }
                        }
                    }
                }
            });
            return combo;
        }
    
        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 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);
             return colorMap;
        }
    }

  2. #2
    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?

    You might be able to save the present highlights into a list
    The highlights are already stored in an Array

    Java Code:
    Highlighter highlighter = textPane.getHighlighter();
    Convert the mouse point to an offset using the JTextPane.viewToModel(...) method
    Loop through the highlights until you find the highlight you want to remove and then remove it.

  3. #3
    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?

    Yes I found that in the API: Highlight[] highlights = highligter.getHighlights();
    and I did use the JTextPane.viewToModel(...) method before!
    For the moment I can not see how to identify the highlight I want to remove,
    but I am looking into it right now, thanks!

  4. #4
    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?

    But since I have a textpane.addCaretListener(new CaretListener() {.....
    I do not really need the JTextPane.viewToModel(...), right?
    I could select* over the placed highlight, which would give me the begin and end offset
    of the marked highlight.... But how do I find the corresponding array index or
    how would I identify that particular highlight?

    *another problem is that select does not seem to work over a highlight
    a kind of awkward thing!

    btw let me first print out a added sequence of highlights to see what it shows!

  5. #5
    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 you add this string to the combo items: "print h-lights" (line 62)
    and the following code to the public void actionPerformed(ActionEvent event)

    Java Code:
     if (comboitem.equals("print h-lights")) { // print highlightd
                            Highlight[] highlights = highligter.getHighlights();
                            for (int i = 0; i < highlights.length; i++) {
                                System.err.println(i + " highlight <" + highlights[i] + ">");
                            }
                        }
    it prints after adding 5 highlights this:

    0 highlight <javax.swing.text.DefaultHighlighter$LayeredHighli ghtInfo@1af0b4a3>
    1 highlight <javax.swing.text.DefaultHighlighter$LayeredHighli ghtInfo@30e34726>
    2 highlight <javax.swing.text.DefaultHighlighter$LayeredHighli ghtInfo@195428dd>
    3 highlight <javax.swing.text.DefaultHighlighter$LayeredHighli ghtInfo@6446d228>
    4 highlight <javax.swing.text.DefaultHighlighter$LayeredHighli ghtInfo@658f7386>

    So how to match this with the character offset which I get from the caret or the JTextPane.viewToModel(...) ?
    Last edited by willemjav; 03-17-2014 at 04:42 PM.

  6. #6
    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 am working on different fronts!

    I found that when getting a list of the highlights like this:
    Highlight[] highlights = highligter.getHighlights();

    You can actually ask for the character offset of, for instance,
    the first highlight like this
    int startoffset = highlights[0].getStartOffset();
    int endoffset = highlights[0].getEndOffset();

    So if I can get the caret working over the yet installed highlight*,
    I could see if the actual new selection merges with and excisting selection
    and finally change it!

    *once an highlight is painted one can not get an selection to appear over it!

  7. #7
    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?

    The thing is this: when you have a small application that adds some different highlights and even remove
    some of them is "no big deal" and I can do that!

    But think you are at a text wrier and you marked some important text yellow.
    But suddenly you changed your mind about some of these marks, right?
    So what you do next? You want to get rid of them right?

    So what is the strategy? Go over them and paint them white?
    Is painting a highlight white equal to removing it?
    and what happens when you remove only a part of the highlight?

  8. #8
    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?

    BIW the two short if statements should be outside of the while loop,
    but inside the actionPerformed, at the above code of the first post.

  9. #9
    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?

    Placing a highlight is no big deal and I showed that with the previous code sample (one needs a color-string,
    which I get from the combo and the text range, which I get from the caret listener).

    But re-placing the highlight is a different story and here is what I figured out:
    1) How to paint over an existing highlight when doing a new selection?
    2) How to replace (partly) an existing highlight?

    To start with 2) imagine a new selection has been made at the text pane. I first should check (when the client enters in
    the highlight dialog window) if the selection is a new highlight or it intents to (partly) replace an existing highlight, right?

    a) if (dot != mark) // (which I get from the caret listener) means a selection has been made
    b) next I check if this selection overlaps with an existing highlight (when not I simply paint a new highlight)?

    Java Code:
    for (int i = 0; i < highlights.length; i++) {
                startoffset = highlights[i].getStartOffset();
                endoffset = highlights[i].getEndOffset();
                
                if ((dot > startoffset && dot < endoffset) || 
                        (mark > startoffset && mark < endoffset) ||
                        (mark < startoffset && dot > endoffset)) { }// highlight hit    
                etc . . . .
    So ones I get the new selected color of the client I can take that particular highlight out
    and paint a (partial) new one, right?

    I am not sure how to deal with the first problem?
    I could of course, when I moving the caret, check constantly for a existing highlight hit (which is kind of silly).
    Ones I hit an existing highlight I could ask for the FontMetrics and paint a box manually while dragging the mouse?
    And what about a LayeredHighlighter, I haven't looked into that one yet?

    Man, each "small" issue turns into a project with enormous consequences (that was what you both talked about gimball2 and kevin)…..
    Last edited by willemjav; 03-20-2014 at 01:26 PM.

  10. #10
    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 the bottom line is that I need to draw the text selections myself.
    So I need to customize a system method that does the drawings
    or I need to dis-able it?
    Any suggestions?

    Or in other words: what paints the standard text selections in JTextPane:
    1) the JTextComponent
    2) or the Caret

    So I noticed when I do this: textpane.setHighlighter(null);
    I have no text selection at all (a bit too radical).
    So here I have a start to construct my own highlighter!
    (I did no realize that the the text selector for copy etc. is actually the highlighter itself,
    kind of stupid, right!
    Last edited by willemjav; 03-21-2014 at 09:08 AM.

  11. #11
    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?

    Ok I have some idea what to do.
    First I have to look into what deinstall does:

    Java Code:
    textpane.setEditorKit(styleEditKit);
            Highlighter highlighter = textpane.getHighlighter();
            highlighter.deinstall(textpane);
    Than I have to "install" my own highlighter (and color probably grey) and in case a highlight gets added
    I have to probably use the layered highlighter to paint a new selection over the
    already present highlight?

  12. #12
    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?

    Just say YES or NO as a comment?

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

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

    You can wait for Camickr (or someone else who is an authority on Swing) to reply yes or no, or you can just go ahead and experiment.

    (I'd just go ahead and try to figure it out)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  14. #14
    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 would ask Camickr this: how could I take control of a text component's highlighter?
    A JTexPane eg. has its own highlighter installed when selecting for instance a line of text.
    It's color is blue by default. How I could eg change the selected color of each selection in green
    (and I am not talking in adding the usual highlights but about those the component adds by itself).
    Maybe what I need to do is to put the highlight off (textpane.setHighlighter(null);) and
    manage all by myself through the caret listener, getFontMetrics(null), and draw a bounding box when dragging...
    lots of work to do....

    The BasicTextUI class is responsible for drawing the standard text component highlight when selecting
    text for paste etc. But I do not know how to manage that class...
    Last edited by willemjav; 03-21-2014 at 02:50 PM.

  15. #15
    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?

    (gimball2 I started reading this book Beginning JSP, JSF and Tomcat: Java Web Development: Giulio Zambon: 9781430246237: Amazon.com: Books
    concerning web application with Java/ an introduction. Is it any good or you have a better idea?)

  16. #16
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

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

    I don't know that book but the reviews look good enough. I also don't know what you want to achieve so I can't say if the book is relevant to you or not.

    I suggest you give this free online book a read; it is what taught me the trick of the trade a long time ago and I've been recommending it ever since:

    Free Online Version of Core Servlets and JavaServer Pages (Second Edition) in PDF

    With the information in both books I'm sure you can get a good understanding of the basics. But that's all woefully off-topic in this thread, in the future I would advise you to start a new thread for a new question.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  17. #17
    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?

    First I will continuo to further boost up my basic Java understanding.
    Than I'd like to get into web-applications with Java (data-base stuff, surfer, and Java)
    What do you think?

    ps I studied already some basics of Apache_Tomcat and MySQL!
    Last edited by willemjav; 03-21-2014 at 03:26 PM.

  18. #18
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

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

    I think you're wise to do it in that order, yes.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  19. #19
    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?

    First we must clarify the terms "selection" and "highlight". Basically a selection is a temporary highlight. When you click somewhere else in the text component you lose the selection. All text component Actions (copy, paste, bold, italic, font size...) work on the selection. So in your application you first select the text you want to highlight with a different Color and then you apply the highlighting.

    Swing text components use Actions to implement the functionality. So in your case I would guess you need to create a HighlightAction which should extend TextAction. You extend TextAction because this class has methods that allow you to access the last text component that had focus. When you want to highlight the selected text you would use the getSelectionStart/End() methods of the text pane, not the mark/dot methods of the Caret. While these values are the same you want to deal with the text pane method. Your HighlightAction would accept the "highlight color" as a parameter. You would then add this HighlightAction to your combo box. When the item is selected from the combo box you would cast the object to your HighlightAction and then invoke the actionPerformed() method of the Action. Since you are adding the actual Action that you want to invoke to the comboBox you will also need to use a custom renderer to display the "name" of the Action.

    Then you can create other Actions, like LastAction or RemoveAllAction as required. There is no need for you LinkedHasMap and the actionPerformed() of the combo box would be the few lines of code described above.

    *another problem is that select does not seem to work over a highlight
    Java Code:
    JTextPane textPane = new JTextPane();
    DefaultHighlighter highlighter =  (DefaultHighlighter)textPane.getHighlighter();
    highlighter.setDrawsLayeredHighlights(false);
    How I could eg change the selected color of each selection in green
    Java Code:
    textPane.setSelectionColor(...);

  20. #20
    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?

    camickr, I am impressed, you really do know some swing-magic: wow!
    So beginning from the second part of your post, the next code
    solved the problem of repainting highlights and "selecting" (and yes I know the difference now)
    on top of a present highlight:

    Java Code:
     DefaultHighlighter.DefaultHighlightPainter p =
                              new DefaultHighlighter.DefaultHighlightPainter(value);
                         DefaultHighlighter highlighter = (DefaultHighlighter) textpane.getHighlighter();
                         highlighter.setDrawsLayeredHighlights(false);
                        
                         DefaultHighlighter actualHighlight = (DefaultHighlighter) 
                                            highlighter2.addHighlight(mark, dot, p); // will look into getSelectionStart/End()
    But still the elaborated part, turning a highlight into an action! The makes perfect sense but I have to figure
    that out first! And I supose that once I have that action, the action will add itself onto the style document, right?

    once again, many thanks!

Page 1 of 2 12 LastLast

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
  •