Hello everybody,
I've been trying to dynamically re-size a frame, according to what font
I wish to use in it. I first create a new Font () class, with whatever
font I want (in my case, "Monospace". Then I wish to make the frame 80
characters wide, but I am not quite sure how to do this, since the only
way I currently know is to pass an 80 character long string to
Font.getStringBounds (), along with an instance of the
FontRenderContext class. But the only way I have of getting an instance
of this FontRenderContext class is to get it from a Graphics object,
which I only access in a JPanel, that I add to my JFrame. So basically
I cannot get the width of an 80 characters long string until I have
created a JPanel to add to my JFrame, which is too late for resizing.
Here's some code:
class myFrame extends JFrame {
public myFrame () {
myPanel aPanel = new myPanel ();
this.getContentPane ().add (aPanel);
}
void setS (int x, int y) { // otherwise myPanel calls its own
setSize ()
setSize (x, y);
}
private class myPanel extends JPanel { // so I can access setSize
()
public void paintComponent (Graphics g) {
super.paintComponent (g);
Graphics2D g2 = (Graphics2D)g;
Font aFont = new Font ("Monospace", Font.PLAIN, 12);
g2.setFont (aFont);
FontRenderContext context = g2.getFontRenderContext ();
Rectangle2D rect = aFont.getStringBounds ("[80
characters]", context);
int height = (int) rect.getHeight ();
int width = (int) rect.getWidth ();
setS (width, 50 * height); // doesn't work
}
}
}
So basically I don't know how to access a Graphics object in the JFrame
object, so that I can call getFontRenderContext, and calculate the
length of the string and all that.
Please note that I am beginning Java, and have not been programming in
this language for very long at all ;-).
Thanks a lot in advance for any help!
- Joseph Paterson
Roedy Green - 22 Sep 2005 10:55 GMT
>I've been trying to dynamically re-size a frame, according to what font
>I wish to use in it.
Another way to do it is to put the contents into the frame then call
pack to scrunch it down to the minimal size that will fit. See
http://mindprod.com/jgloss/pack.html
see http://mindprod.com/jgloss/fontmetrics.html
for how to get a dummy Graphics context that will in turn give you the
FontMetrics

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.