Setting height of (two) JEditorPanes regardless of the font used

39 views Asked by At

Is there a way in Java Swing by which we can find the exact possible height needed to display a line of text regardless of the font/font size used?

I an using a JEditorPane and I wanted the height to be in sync with another editor pane in the same panel. Basically the whole idea was to let both the editor panes have same height depending on the text in them.

Note: I have a listener in place which keep changing the height of these two panes based on the text in them, so that if I edit the code in one of these panes and the height becomes greater than the other, the new height (of both the panes) should be the height of the highest one.

See the following code for the approach that I followed..:

//find the height of the pane based on the contents that is to go into them. This will
//count the number of newlines in the both the strings and will return the maximum.
//For eg if string 1 contains 3 newline chars and string 2 contains 5 chars the
//function will return 5.

int height= findheight(String str1,String str2);

JEditorPane pane1= new JEditorPane();
JEditorPane pane2= new JEditorPane();

pane1.setText(str1);  
pane2.setText(str2);

pane1.setSize(new Dimension((int) pane1.getPreferredSize().getWidth(),16*height));
pane2.setSize(new Dimension((int) pane2.getPreferredSize().getWidth(),16*height));

The value 16 in the above code is for a lets say a x font having font size y, if we change the font or font size the display will not fit. Is there a workaround or is there an inbuilt function that determines the height needed?

0

There are 0 answers