I want to get the height of a string. Here is what i mean:
Say I have string : Hi , then I want the height(Hi) as the max height among all the characters in that string, so it will be the height of H. I saw few posts which said to use graphics to measure it, but i am not printing it, but i just want the height!
If I can get the height of character then i will write a loop to see which is the highest height!
So either of the two is fine:
Get height of string(max height among all letters in string) or
Get height of specified letter!
Asked
Active
Viewed 813 times
1

Destructor
- 3,154
- 7
- 32
- 51
-
Wouldn't you also have to specify which font all of the characters are displayed in? (I actually wouldn't be terribly surprised if what you want is doable) – Dennis Meng Oct 24 '13 at 06:22
-
http://stackoverflow.com/questions/368295/how-to-get-real-string-height-in-java – Linga Oct 24 '13 at 06:23
-
@ling.s i saw that. do i need to extend JPanel? My code is not using JPanel! – Destructor Oct 24 '13 at 06:29
-
@DennisMeng i am using default font! so I am wondering if eclipse could return height using default font? – Destructor Oct 24 '13 at 06:30
-
So something like Courier? (Also, "default" won't really help if your code can be run on places with different defaults.) – Dennis Meng Oct 24 '13 at 06:36
-
The height of it in what font? weight? point size? Your question doesn't make sense without specifying those, which takes you into `Graphics` land. – user207421 Oct 24 '13 at 06:58
1 Answers
4
Just use the method GC#textExtent()
to get a Point
with the height and width of the text:
public static void main(String[] args)
{
final Display display = Display.getDefault();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
GC gc = new GC(display);
System.out.println(gc.textExtent("Hi").y);
gc.dispose();
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Javadoc:
Returns the extent of the given string. Tab expansion and carriage return processing are performed.
The extent of a string is the width and height of the rectangular area it would cover if drawn in a particular font (in this case, the current font in the receiver).