๐Ÿš€ go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.swing
Article #10758

Re: How to know the size in pixels???

#10758
From: Paul Furbacher [TeamB]
Date: Tue, 17 Aug 1999 00:00
56 lines
2162 bytes
David Vรกsquez Estrada wrote:
> 
> nlaan wrote:
> 
> > Sorry, my mistake the correct method is used as followed:
> >
> > public void paint(Graphics g)
> > {
> >     FontMetrics fm = g.getFontMetrics();
> >
> >     int width = fm.stringWidth("Hello World");
> >
> >     int height = fm.getHeight();
> > }
> >
> 
> Should I override the method paint of "some" kind of class or I can get an
> instance of the Graphics class, since the graphics class is also an abstract
> class.

There are a number of ways to get what you want without
having access to a graphics context as in the example above.
Assuming a JLabel called 'myLabel':

   FontMetrics fm = myLabel.getFontMetrics(myLabel.getFont());

   int width = fm.stringWidth(myLabel.getText());

   // etc.

You can even grab a graphics context

   Graphics g = myLabel.getGraphics();
   FontMetrics fm = g.getFontMetrics(myLabel.getFont());
   // ...

However, when you are done with this, call

   g.dispose(); 

I forgot about doing this in a library I recently wrote and someone
wasn't very happy when he found a big memory leak!  Oops, it
just sort of slipped my mind ....

But don't call 'g.dispose()' in a method which gets its 'g' as a method
parameter.  You do that, and boom, any code which shares that graphics
context ends up trying to work with a null pointer.


Paul Furbacher  (TeamB)
Technical Details
Message-ID: <37B9DDB8.E8BF0C80@bilbo.bio.purdue.edu>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <37B18BC5.FDC58523@ucbcba.edu.bo> <7ovhp2$g7u11@forums.borland.com> <37B43577.DF127B44@ucbcba.edu.bo> <7p1peb$ijd1@forums.borland.com> <37B9C689.E8094E77@ucbcba.edu.bo>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII
X-Google-Thread: 111d45,db95dab94e8fcb9e
X-Google-Attributes: gid111d45,public
From: "Paul Furbacher [TeamB]" <pf@bilbo.bio.purdue.edu>
Subject: Re: How to know the size in pixels???
Date: 1999/08/17
Message-ID: <37B9DDB8.E8BF0C80@bilbo.bio.purdue.edu>
X-Deja-AN: 513964765
Content-Transfer-Encoding: quoted-printable
References: <37B18BC5.FDC58523@ucbcba.edu.bo> <7ovhp2$g7u11@forums.borland.com> <37B43577.DF127B44@ucbcba.edu.bo> <7p1peb$ijd1@forums.borland.com> <37B9C689.E8094E77@ucbcba.edu.bo>
Content-Type: text/plain; charset=iso-8859-1
Organization: Reverse Alchemy, Inc.
Mime-Version: 1.0
Reply-To: pf@bilbo.bio.purdue.edu
Newsgroups: borland.public.jbuilder.java.swing