Missing Graphics in JComponent or JPanel

From: ThomasH (henrymot_at_any.net)
Date: 11/30/04


Date: Mon, 29 Nov 2004 15:04:29 -0800

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? :-)

Thomas



Relevant Pages

  • JAVA HELP: Beans.instantiate, JTable, JBuilder
    ... just now begun to teach myself Swing. ... I am currently using JBuilder 9, ... and am assembling the GUI using its nice GUI designer. ... and why can you only call the default constructor using this method? ...
    (comp.lang.java.programmer)
  • Re: Swing Programming Question
    ... >>constructor has to be called sometime, ... One of the main problems with Swing based applications is its slow ... most dialogues are generally built based on some specific ... the response - In my experience a delay of upto say half a sec. is ...
    (comp.lang.java.gui)
  • Swing uses bad features
    ... or does Swing do things in a bad way? ... For example, if I subclass a Swing class, that superclass's ... constructor will be executed as the implicit first statement ... setText(), my setTextmethod gets called BEFORE I can ...
    (comp.lang.java.gui)
  • Re: Swing uses bad features
    ... For example, if I subclass a Swing class, that superclass's ... constructor will be executed as the implicit first statement ... This is as all Java constructors work. ...
    (comp.lang.java.gui)
  • Re: New applet project
    ... A web start application (or applet) ... object moving in a window; I have also some text attached to this work ... Note that (java.awt.)Canvas is part of the AWT, ... looking to Swing for good GUI's. ...
    (comp.lang.java.help)