Hi, this seems like a "chicken and egg" problem, but I am sure there is a way to
do this:
In order to compute the height of a JPanel I want to instantiate I need to know
the height of a line of text, which I could do using
JPanel.getGraphics().getFontMetrics().getHeight().
But that doesn't work until I call JPanel.setVisible() (null pointer exception).
But before I can make it visible I need to know its size!
Any suggestions?
PofN - 17 Aug 2006 17:55 GMT
> Hi, this seems like a "chicken and egg" problem, but I am sure there is a way to
> do this:
[quoted text clipped - 8 lines]
>
> Any suggestions?
Write a LayoutManager.
PofN
David Cogen - 17 Aug 2006 23:17 GMT
>>Hi, this seems like a "chicken and egg" problem, but I am sure there is a way to
>>do this:
[quoted text clipped - 12 lines]
>
> PofN
That seems more trouble than it's worth though, and I'm having a hard time
figuring out how it would help in this situation. The design doesn't use a
layout manager currently and I'm not about to redesign from scratch if there is
any other way.
Surely there must be a way to find out what the default font's height will be
before I make the JPanel visible. If I can do this one little thing my problem
is solved. Isn't there?
Jeffrey H. Coffield - 18 Aug 2006 01:59 GMT
> Hi, this seems like a "chicken and egg" problem, but I am sure there is
> a way to do this:
[quoted text clipped - 9 lines]
>
> Any suggestions?
My approach would be to set the height of the JPanel to be the point
size of the font since the point size is the recommended vertical line
spacing on most fonts.
Jeff Coffield
Knute Johnson - 18 Aug 2006 03:55 GMT
> Hi, this seems like a "chicken and egg" problem, but I am sure there is
> a way to do this:
[quoted text clipped - 9 lines]
>
> Any suggestions?
Very easy if you can use 1.5 or later.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test3 extends JPanel {
String str = "Now is the time for all good men to come to the aid";
int height;
public test3(Font font) {
setFont(font);
FontMetrics fm = getFontMetrics(font);
height = fm.getHeight();
int width = fm.stringWidth(str);
setPreferredSize(new Dimension(width,height));
}
public void paintComponent(Graphics g) {
g.drawString(str,0,height);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
test3 t3 = new test3(new Font("Arial",Font.BOLD,24));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(t3,BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}

Signature
Knute Johnson
email s/nospam/knute/
jvsoft.org@gmail.com - 18 Aug 2006 09:08 GMT
> > Hi, this seems like a "chicken and egg" problem, but I am sure there is
> > a way to do this:
[quoted text clipped - 51 lines]
> Knute Johnson
> email s/nospam/knute/
Please see Java font tutorial
http://www.developerzone.biz/index.php?option=com_content&task=view&id=92&Itemid=36