salbeira
salbeira

Reputation: 2611

Swing Component with automatic line wraping and limited width with HTML support

I want to implement a small tooltip with a scrollbar like the one in eclipse that appears when hovering above a class or member.

The problem I have is finding a way to limit only the width but not the height of a component within the scroll pane I have inside my tooltip. The component should support HTML and also wrap the text correctly when it exceeds the width of the inner bounds, but all components I have tried out have either line wrapping or HTML rendering, but not both

A way to limit only width is also nowhere to be found as every "setXSize" where X is "preferred" "max" "min" etc. all require two arguments and there is no "setMaxWidth" method for components.

Setting "setMaximumSize(new Dimension(256, Integer.MAX_VALUE);" would seem like a solution but it doesnt work as parameters set by "max" and "min" are ignored most of the time which is quite frustrating.

On request a current example of the implementation:

public class MyTooltip extends JTooltip{
    private JScrollPane scroll;
    private JEditorPane pane;

    public MyTooltip(String htmlCode){
       this.pane = new JEditorPane();
       this.scroll = new JScrollPane(this.pane);
       this.pane.setEditable(false);
       this.pane.setContentType("text/html");
       this.scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

       //Here the problems begin
       this.pane.setMaximumSize(new Dimension(512, Integer.MAX_VALUE));
       this.scroll.setMaximumSize(new Dimension(512, Integer.MAX_VALUE));
       this.pane.setText(htmlCode);

       this.add(scroll);
    }
}

Upvotes: 0

Views: 330

Answers (2)

salbeira
salbeira

Reputation: 2611

Ok, the whole problem just solved itself: One had the idea to let the user write his own texts to be displayed on the tooltips, but that included letting him use multiple "spaces" for indentation when he called for it.

To let HTML render this as intended we replaced every "space" with an & nbsp; so no optimization on gaps between characters would be performed, but this of course has the result that no algorithm for automatic line wrapping would accept any "gap" between words as a suitable place to break the line.

So our implementation actually works as intended, only the Strings we give the tooltip to display are not suitable to be line broken.

Upvotes: 0

StanislavL
StanislavL

Reputation: 57421

Have you tried JTextPane with HTMLEditorKit (content type text/html)?

I think that's what you need.

Upvotes: 1

Related Questions