findind how many characters in some amount of pixels.

B

Bharath

Hi ,

I am working on JTable data printing.In that i have some problem.If
anyone can help me,please help me.

how to find the no.of characters in some amount of pixels ?

TableColumn tk = colModel.getColumn(nCol);
int width_1 = tk.getWidth();
finding string width using
fontMetric.stringWidth(string);

how to substring the string based on coloum width and string width
which will fit into the particular column.

If anybody knows solution for this problem, Please give me the reply.

thanking you
Bharath
 
D

David R. Conrad

Bharath said:
Hi ,

I am working on JTable data printing. [...]

how to find the [number] of characters in some amount of pixels ?

[...]

how to substring the string based on coloum width and string width
which will fit into the particular column.

The most straightforward solution is to repeatedly cut down the string
until it does fit. I will assume you want to append an ellipsis to
indicate to the user that the string has been shortened.

If Bharath does not fit, try Bharat...
If Bharat... does not fit, try Bhara...
If Bhara... does not fit, try Bhar...

etc.

You could also approach it from the other end, and try B... (or even
just ...) and then grow the string until you found the largest substring
that would fit.

If the font is proportional, not monospaced, there is no way to find a
substring that fits without calling stringWidth() on some candidate
substrings. A trial-and-error approach is needed. There are a few
optimizations that could be made, but since the strings will typically
be fairly small and this is UI code, it is probably not worth optimizing
it even though the algorithms described above are O(n^2) (remember,
stringWidth() will have to look at each character of the candidate
substrings you pass it).

The optimizations that come to mind are: 1) cut the string down as if
it were monospaced, and work your way towards the answer from there.
For instance, say we've got a 23-character string and the available
space is only enough for 60% of it. Instead of trying 22, then 21,
etc. we start from 60% of 23 (about 14), and see if that fits. Then
work up (15, 16, ...) or down (13, 12, ...) until we get what we need.

2) Binary search. This is the logical extension of the previous
optimization, but it is almost certainly overkill in this situation.
Only do this if you really need it, or you wear a propeller beanie.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top