I have a JTextField which can accept a fixed number of characters (eg. 10 characters). I want to restrict the width of the TextField to exactly take that many characters. So given the no.of characters, is there a way to find out the width (pixels) it will take? Assume that we know the font.
This will get you the exact width, though you'd want some extra pixels of padding to make it pretty.
myJTextField.getFontMetrics(myFont).stringWidth(myString);
This approach only makes sense for unproportional fonts. Otherwise you'd had to find the 'biggest' char in the charset to make the box wide enough for 10 chars of this type.
A practical approach would be to 'guess' a wide character and compute the width so you a good propability that the text field will be big enough for usual input. Adapting lins314159 example code:
myJTextField.getFontMetrics(myFont).stringWidth("wwwwwwwwww);
JTextField textField = new JTextField(10);
The UI will size the text field automatically. I believe it does in fact use a "W" as the sizing character, so it most cases it will be larger than you need. If you want the width to be exact then use a monospaced font.
Related
I'm looking for a way to get the number of characters that can appear in a row in a JTextArea.
I tried using getColumns() but this returned 0:
jTextArea.getColumns();
Does anyone know how this can be achieved? I need it so that I can display data in fixed width columns, so I need the number of characters that can fit in a row in order to calculate this.
If you don't specify number of rows and columns when creating JTextArea, it default the rows and columns to zero. This mode allows the JTextArea to expand/contract according to available space for itself and actual number of letters shown in a line etc can be adjusted.
In the default mode, the number of letters that would fit in a line will depend on the current dimension of the component, the line wrapping style (word boundary or character boundary) and the font used.
If you cannot set the row, columns in the JTextArea then you can probably use javax.swing.JTextArea.getColumnWidth() to get the size of one character and use the current width of the component to get approximate number of letters that will fit in a line.
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.
Apparently if the columns size is more than 70 the field get's displayed with a size where you cannot even type a single character?
I'm talking about:
new JTextField(70);
Passing in the number of columns adjusts the text field's preferred size. As camickr points out, you may be using a layout that under certain circumstances will use the minimum size which is zero.
If you wish to force the minimum size to be the preferred size (and that may or may not be a good idea), you can do:
textField.setMinimumSize(textField.getPreferredSize());
My guess is that you are using a GridBagLayout. If there is not enough space to display the component at its preferred size the component shrinks to its minimum size which I believe is 0. Try giving your component a minimum size or use a different layout manager.
If you need more help post your SSCCE.
First problem: You have 400 pixels width to go on, and need to fit some text within that constraint as large as possible (thus, the text shall use that amount of space).
Throw in a new constraint: If the text is just "A", then it shall not zoom this above 100 pixels height (or some specific font size).
Then, a final situation: Linebreaks. Fit some text in the largest possible way within e.g. 400 x 150 pixels.
An obvious way is to simply start with point 1, and then increase until you can't fit it anymore. This would work for all three problems, but would be very crude. The fitting of a single line within bounds could be done by writing it with some fixed point size, check the resulting pixel bounds of the text, and then simply scale it with a transform (the text scales properly too then, check out TransformUI).
Any ideas of other ways to attack this would be greatly appreciated!
As what you are modelling is complex, especially with line breaks, then your initial proposal of trying all sizes is along the right lines, especially if it needs to be accurate.
However, rather than testing each value, you can use a binary search to find the appropriate font size. You know the size is somewhere between 1 and 100 (your upper range). using a binary search, each test sets the font size and checks the resulting layout. If the text is too large, then we search the lower half of the current range of possible values. If the font size fits, then we search the upper half. Your search will use at most 7 attempts (100 log base 2 rounded up), it will be exact, finding the largest size without going over, and it will be flexible if you need to add more requirements later, such as a mix of fonts or more stringent constraints on the layout.
I'm assuming you are using a text component that does line wrapping, and that you can set the maximum width to 400. So, you set the font size and it does the layout giving you back the required height, laying out text within the given width.
You can use hints to try to guide the algorithm to the result quicker, such as making your first guess close to the expected size, but text rendering is fast, that the performance increase may not be worth the implementation effort.
See Wikipedia - Binary Search Algorithm
I would do the following:
Assume you want W pixels wide text.
Pick an arbitrary size, say 10pt, and see what bounding box the text-string gets for that size. Lets say it gets N pixels wide.
Set the new size to 10pt * W/N, and repeat from step one, until you get within a reasonable threshold. (Hopefully it would work within one iteration.)
This relies on the fact that the width of the string, is roughly proportional to the size of the font.
I'd instantiate the Font at the largest desired size: say 72 for one inch glyphs at 72 dpi. Use TextLayout to get the bounds and scale using AffineTransform (direct) or AffineTransformOp (offscreen), while preserving the aspect ratio. Suitable RenderingHints help, too.
I plan on making a multi comparison program. It will compare multiple files by displaying N number of files in a grid where N = X * Y. X and Y are the width and height of the grid elements. Easy enough, I know how to do this pretty much.
The question:
How do and in what way is best to highlight individual characters in each of these grid elements? I plan on highlighting matching text that is found in the same position.
I'd use a JTextPane rather than a JTextArea, and read up on the StyledDocument class. This will give you all sorts of options.
You could use a JTextArea with a Highlighter. See the second example on this page for how.
I'm not sure what you mean by "Highlight the characters", but to bring attention to grid elements, or pairs of grid elements, you could set the background color of the appropriate component.