In Java when the text of the JLabel could not be displayed due to lack of space the text is truncated and "..." is added in the end.
How can I easily find out if currently JLabel displays full text or the truncated?
EDIT:
I see that there is a way to find out the size of the text by using FontMetrics. However this solution doesn't fully answers the question. In the case the text of JLabel contains HTML decorations the metrics.stringWidth() would also calculate width of HTML tags. So it could happen that result of metrics.stringWidth() would be grater than JLabel's width but still the text would be displayed correctly.
Is there a way know what decision took the JLabel itself while displaying the text. Has it decided to truncate the text or not.
The ellipsis is added by the label's UI delegate, typically a subclass of BasicLabelUI, as part of it's layout and preferred size calculation. The method layoutCL() may be overridden to examine the geometry, as shown on this example.
As a practical matter, I'd ignore the elision and show the full text in a tool tip.
From Oracle - Measuring Text:
// get metrics from the graphics
FontMetrics metrics = graphics.getFontMetrics(font);
// get the height of a line of text in this font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);
Compare size to the size of the JLabel.getSize();
I suppose if the component's preferred size is greater than it's actual size, then you can expect truncation. In order for this to work, of course, the component must already be realized.
Check this and see the layoutCompoundLabel() method. It returns a String representing the text of the label. You can compare it to the original to determine if it will be clipped.
Jim S.
The usual way to do this is to use a method that calculates the expected size of the text as it will be displayed in the label. If you're using a monospaced font, this is easy:
lengthOfChar * numChars
If you're not using a monospaced font, it's obviously much harder. I think there are some utilities around that will attempted to calculate this.
Once you have the size of the displayed string, you can compare to the length of the JLabel and see if the label is too small.
To get sizes of html text check this https://www.java.net/node/665691.
View view = (View) javax.swing.plaf.basic.BasicHTML.createHTMLView(label, value.toString());
int width = (int) view.getPreferredSpan(View.X_AXIS);
int height = (int) view.getPreferredSpan(View.Y_AXIS);
The only small problem is that it might have issues with non-html text. So, just use font metrics for non-html strings. The following worked perfectly for me:
if (value.toString().startsWith("<html>")) {
View view = (View) javax.swing.plaf.basic.BasicHTML.createHTMLView(label, value.toString());
width = (int) view.getPreferredSpan(View.X_AXIS);
}
else {
width = (int) label.getFontMetrics(label.getFont()).stringWidth(value.toString());
}
Related
I'm using a JTextPane to display a kind of bus ticket that uses a monospaced font. I am using StyleConstants and SimpleAttributeSetto set bold and italic text, but I would like to also use double width and height characters. I don't want to make a double-sized font, by double I mean that a character 'A' which I want to be double-width, would get stretched in width, but not in height, and vice versa for double-height, like in this image I found here.
I really don't know any method to do so and googling didn't give me an answer. Maybe a way to adjust the size of a font horizontally and vertically?
To adjust the size of a font to double width:
// Input: an existing Font object called 'font'.
final int style = Font.PLAIN;
AffineTransform transform = new AffineTransform();
transform.setToScale(2.0, 1.0);
Font doubleWidthFont = font.deriveFont(style, transform);
I haven't tried this code, so please let me know if it doesn't work exactly as written.
Even though it's for JEditorPane, but also should work with JTextPane
http://java-sl.com/tip_text_height_measuring.html
I need to get height and width of the textView's text.
Yes there is a method called textView.getTextSize(), but I don't understand what that size means: a height, a width or something else? I need the exact width and height values (it will be good, if values will be in pixels not sp).
One approach could be with the use of getPaint() and getTextBound()
String text = (String) textView.getText();
Rect textBound = new Rect();
textView.getPaint().getTextBounds(text,0,text.length(),textBound);
int textHeight = textBound.height();
int textWidth = textBound.width();
I am not entirely sure of the height and width being in pixel. Based on this Q&A in regards to RectF, I believe Rect as well should use pixels.
getTextSize() returns the TextView's line height in pixels.
I think what you're looking for is textView.getLayout().getHeight() and textView.getLayout().getWidth(), although the Layout can be null if the TextView changed recently.
getTextSize() returns the size of the text set on the which is effectively the font size of the TextView, you can determine this by looking at the setTextSize method:
https://developer.android.com/reference/android/widget/TextView#setTextSize(int,%20float)
To figure out the height/width of a TextView you could use:
https://developer.android.com/reference/android/view/View#getMeasuredHeight()
https://developer.android.com/reference/android/view/View#getMeasuredWidth()
This is assuming that the view has been measured and laid out.
As for useful conversions that could be helpful here refer to:
How to convert DP, PX, SP among each other, especially DP and SP?
Whenever unsure about what a method does, check the docs and also check other methods to figure out what it does, like you can figure out what getTextSize returns by looking at setTextSize.
I'm using a fixed cell height to create a table.
If the font size is too large, the text is not visible in the table.
Is there a built-in function in iText that automatically reduces the font size to the maximum possible size, or do I have to implement this by myself?
Automatic font size is only possible in the context of AcroForm text fields. When you define the font size of a text field as 0, then a font size is chosen that fits the rectangle. In the case of a fixed cell height in a table, you are responsible to make sure that the text fits.
If you're concerned about the height, please take a look at the FitTextInRectangle example:
BaseFont bf = BaseFont.createFont();
int textHeightInGlyphSpace = bf.getAscent(text) - bf.getDescent(text);
float fontSize = 1000f * fixedHeight / textHeightInGlyphSpace;
This example was written in answer to Correct text position center in rectangle iText
If you're concerned about the width, then you need to use the getWidthPoint() method as explained here: How to calculate the string width in iText?
BaseFont bf = BaseFont.createFont();
float width = bf.getWidthPoint("My text", myFontSize);
You'll need to make sure that width doesn't exceed the width of the cell. To achieve this, you'll need to adjust myFontSize.
See my answer to this question: How to choose the optimal size for a font?
I had posted the same question in oracle javafx forum too but haven't got a response. So trying my luck here.
I have a requirement where in the content of the text area is dynamically populated from the database. I am able to successfully retrieve and display the data on the text area.
However when the content is too large, I am not able to dynamically set the height of the text area. When I try to display the same as a label, the display is flawless, dynamically sets the height as per the content. So, I tried to create a label, with same content and dynamically bind the height to the preferred height as below, but it doesn't work.
// Generate User Note Description
TextArea textArea = new TextArea();
Label text = new Label();
// SETTING THE TEXT TO A LABEL TO RETRIEVE THE HEIGHT
text.setText(usrNotes.getNote().trim());
// ALWAYS DISPLAYS 0.0
System.out.println("height::"+text.getHeight());
if (isMyNote) {
// ALWAYS SETS TO THE MINIMUM HEIGHT OF 60.0
textArea.setText(usrNotes.getNote().trim());
textArea.setPrefWidth(Screen.getPrimary().getVisualBounds().getWidth() - 500.0);
textArea.setWrapText(true);
textArea.setMinHeight(60.0);
// WITHOUT THIS BINDING, DISPLAYS LOT OF EXTRA SPACE AFTER THE TEXT
textArea.prefHeightProperty().bind(text.heightProperty());
textArea.setStyle("-fx-padding:0 5 2 1; -fx-font-size: 1.1em;-fx-background-color:white");
} else if (!isMyNote) {
// THIS IS PERFECT, AS EXPECTED SETS THE HEIGHT DYNAMICALLY
text.setText(usrNotes.getNote().trim());
text.setStyle("-fx-padding:0 5 2 1;");
text.setStyle("-fx-border-color: white;-fx-font-size: 1.1em;-fx-background-color:#F5F5F5;");
text.setWrapText(true);
text.setPrefWidth(Screen.getPrimary().getVisualBounds().getWidth() - 500.0);
text.setMinHeight(60.0);
}
I would highly appreciate if someone can provide a hint on how to resolve this issue.
Thanks -SV
The reason text.getHeight() returns 0, (and therefore have to bind to text.heightProperty()) is because the height isn't calculated when the component is constructed. It is calculated when the component is rendered to the screen.
If you want to calculate a height ahead of time, I believe you will have to use something like FontMetrics (http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html) to calculate the width and line height of your string, break up the string into tokens to figure out where line breaks will fall (based on your width), and then figure out how many lines you will need (and therefore, how high your TextArea needs to be).
From an xml file, I'm given a width, height and id. All of them can and do vary very quickly. Now, I'm asked to draw a rectangle using the width and height (an easy task), and place the id at its center. The id must not overflow out of the rectangle it's contained it.
For single-character strings, this is also easy - set the font size to the height, play a bit with the x position maybe, and it's centered. The problem is when it's multi-character strings.
So given a width and height and a string, how can you determine what font-size the string should appear in? Assume you have every bit of information you need on the rectangle you're drawing the string in.
[Edit]: I'm using the Graphics 2D class to draw everything.
Start with selecting a Font at your preferred (i.e. maximum) size.
Grab the FontRenderContext from your Graphics2D object using getFontRenderContext.
Use getStringBounds() on the Font to be rendered to get a Rectangle2D object for the specific String to be rendered. That object describes the final size of the String using that Font
Check if the size specified by that Rectangle2D is small enough.
4a. If it is small enough, you're done. Use the last Font you've checked.
4b. If it is too big, use Font.derive() to produce a smaller version of the Font and continue to use that and loop back to 3.
Don't quite have the time to give you a full working example, but here are a couple pointers that should get you going in the right direction. The graphics object you are using to draw with has a getFontMetrics() method, one of the methods on FontMetrics is stringWidth(String str) which gives you the width of a string in the current Font.
If the width is too big for your rectangle set the Font on the Graphics object to the same font just with a smaller size until it fits.
To horizontally center a string in a container (learned long ago in typing class in high school):
(rectangleWidth / 2) - (stringWidth / 2)
http://download.oracle.com/javase/1.5.0/docs/api/java/awt/FontMetrics.html
To create a Font with a smaller size, something like:
Font font = graphics.getFont();
Font smallerFont = font.derive(font.getSize() - 1);
graphics.setFont(smallerFont);
Hope this gets you going in the right direction.
I would recommend for this problem to remove as many unknowns as possible. In this case, the problem chiefly is that font characters can vary in width... well most. That's why I would use a good monospace font like courier new for the ID, that way you know what the width of each character is, you know the width of your rectangle and you know the number of characters in your string. You can simply reduce the pixel size of each character will till your string fits the available width.
Example, if the width of each character is 12px and you have 10 characters in your ID, then you need 120px to fit everything in. If you only have 80px available, it's simple math 80/10 = 8px font-size (reduce half a pixel for padding if you want.
Just my suggestion.