Re: Missing Graphics in JComponent or JPanel
From: A. Bolmarcich (aggedor_at_earl-grey.cloud9.net)
Date: 11/30/04
- Next message: Theo: "NoClassDefFoundError-JDK1.5.0"
- Previous message: Murray: "Re: Problems making a Graph"
- In reply to: ThomasH: "Missing Graphics in JComponent or JPanel"
- Next in thread: ThomasH: "Re: Missing Graphics in JComponent or JPanel"
- Reply: ThomasH: "Re: Missing Graphics in JComponent or JPanel"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 30 Nov 2004 00:00:58 -0000
On 2004-11-29, ThomasH <henrymot@any.net> wrote:
> Hi,
>
> I face a strange problem, which bugged me already back than with
> AWT, Swing seems to have the same issue:
>
> I extend JPanel and in the constructor I try to calculate
> its preferred size. This size is related to size of used
> fonts. Thus I do:
>
> Font f;
> FontMetrics=fm;
> construct()
> {
> f=new Font(something);
> setFont(f);
> Graphics g=getGraphics();
> if (g==null) {
> System.out.print("No graphics in contr!!");
> // add ad hoc values to dimension
> } else {
> fm=g.getFontMetrics()
> // perf Form calculations
> }
> }
>
> Now later I can (or rather must) obtain fm and calculate
> the values in the paintComponent();
>
> getGraphics() returns null silently, no exception is
> being thrown. Browsing through the Swing information
> 'booklets,' such as Geary 1200 pages, or the Manning
> Swing 2nd edition 1000 pages yields no help.
>
> What do I do wrong? :-)
What you are doing wrong is trying to get information about a native
screen resource associated with a component before the component's
peer has been created. You should override the addNotify() method
of your extension of JPanel with something like
public void addNotify() {
super.addNotify();
FontMetrics fm = getFontMetrics(getFont());
// calculate the size using the FontMetrics
}
Geary explains it with the FontSelectionPanel example in "Graphic
Java 1.1 Mastering the AWT".
- Next message: Theo: "NoClassDefFoundError-JDK1.5.0"
- Previous message: Murray: "Re: Problems making a Graph"
- In reply to: ThomasH: "Missing Graphics in JComponent or JPanel"
- Next in thread: ThomasH: "Re: Missing Graphics in JComponent or JPanel"
- Reply: ThomasH: "Re: Missing Graphics in JComponent or JPanel"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|