Why does this nullpointer happen

I am trying to create a JLabel which uses the background screenshot, and prints some text on top of it.
I have run into a problem when I attempt to manually set the Font. I think I have narrowed the problem down to the getPreferredSize() method, and I think it is related to the font metrics class. But I cant figure out.
Here is the test code (it doesn't have much applicability, but it illustrates the problem)
If you remove the line: setupImage from the setFont() method, then everything works fine, but unfortunately, I need this to determine the size of my screen capture (like I mentioned before, this doesn't make much sense in my example, but for my application, it is required)
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class LabelTest extends JLabel {
     public static void main(String[] args) {
          JFrame frame = new JFrame();
          LabelTest l = new LabelTest(new Point(100,100));
          l.setFont(new Font("Tahoma", Font.BOLD, 14));
          frame.add(l);
          frame.pack();
          frame.setVisible(true);
        private BufferedImage image;
          private Point point;
          public LabelTest(Point p) {
               this.point = p;
               setupImage();
          private void setupImage() {
               try {
                    Robot r = new Robot();
                    Dimension d = getPreferredSize();
                    image = r.createScreenCapture(new Rectangle(point.x, point.y, d.width, d.height));
               catch(Exception e){
                    e.printStackTrace();
          public void setFont(Font f) {
               super.setFont(f);
               setupImage(); //if you comment this out, everything works
          public void paint(Graphics g) {
               Graphics2D g2 = (Graphics2D)g;
               g2.drawImage(image,0,0,this);
               //draw the labels
               Font f = getFont();
               if(f != null) {
                    FontMetrics fm = getFontMetrics(getFont());
                    g2.setColor(getForeground());
                    g2.drawString("Test", 15, fm.getHeight()/2 - fm.getMaxDescent());
          public Dimension getPreferredSize() {
               Font f = getFont();
               if(f != null) {
                    FontMetrics fm = getFontMetrics(getFont());
                    System.err.println(fm.getHeight());
                    int hieght = fm.getHeight();
                    int width = 0;
                    width = fm.stringWidth("test");
                    return new Dimension(width + 15, hieght + fm.getHeight()*2);
               else {
                    return new Dimension(200, 200);
          public Dimension getMinimumSize() { return new Dimension(200, 200); }
     }

2 Questions for you guys:
1) Camickr: In my code, I wasnt recreating the background image everytime, I was simply drawing it everytime. However, now that I think about it, it would be nice to figure out if the background has changed, in order to take a new picture of it.
2) So I mentioned earlier that I was having trouble with resizing of the label. I was able to narrow it down to a test case, however, I don't know why this occurs.
In the code below, I extend the Window class, and add the JLabel to it. However, you will be able to see that when I change the Font, the resizing doesn't affect the containing Window (You can test this by clicking on the window, you will see that the width is calculated using the original font, before the setFont call).
The wierd thing, is that if I dont subclass Window, and just use a Window instance in my main method, everything works fine. Now I could do this, but I would like to know why this resizing problem is happening.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
public class LabelTest extends Window{
     public static void main(String[] args) {
          JFrame frame = new JFrame();
          frame.setPreferredSize(new Dimension(300,400));
          LabelTest l = new LabelTest(frame, new Point(500,500), "My long string 222333111444555");
          l.setFont(new Font("Tahoma", Font.BOLD, 14));
          frame.pack();
          frame.setVisible(true);
          l.setVisible(true);
     private BubbleLabel bubble;
     public LabelTest(JFrame owner, Point startingPoint, String text) {
          super(owner);
          setupBubble(startingPoint, text);
     public LabelTest(JDialog owner, Point startingPoint, String text) {
          super(owner);
          setupBubble(startingPoint, text);
     private void setupBubble(Point startingPoint, String text) {
          bubble = new BubbleLabel(startingPoint, text);
          this.setLocation(startingPoint);
          this.setLayout(new BorderLayout());
          this.add(bubble, BorderLayout.CENTER);
          this.pack();
     public void setFont(Font f) { bubble.setFont(f); }
     public class BubbleLabel extends JLabel {
          private String myText;
        private BufferedImage image;
          private Point point;
          public BubbleLabel(Point p, String text) {
               this.point = p;
               this.myText = text;
               setupImage();
               this.addMouseListener(exitListener);
          private void setupImage() {
               if(point ==  null) {
                    return;
               try {
                    Robot r = new Robot();
                    Dimension d = getPreferredSize();
                    image = r.createScreenCapture(new Rectangle(point.x, point.y, d.width, d.height));
               catch(Exception e){
                    e.printStackTrace();
          public void setFont(Font f) {
               super.setFont(f);
               setupImage();
          public void paint(Graphics g) {
               Graphics2D g2 = (Graphics2D)g;
               g2.drawImage(image,0,0,this);
               //draw the labels
               Font f = getFont();
               if(f != null) {
                    FontMetrics fm = getFontMetrics(getFont());
                    g2.setColor(Color.GREEN);
                    g2.drawString(myText, 15, 25 + fm.getHeight()/2 - fm.getMaxDescent());
          public Dimension getPreferredSize() {
               Font f = getFont();
               if(f != null) {
                    FontMetrics fm = getFontMetrics(getFont());
                    int hieght = fm.getHeight();
                    int width = 0;
                    width = fm.stringWidth(myText);
                    System.err.println(width + 15);
                    return new Dimension(width + 15, hieght + fm.getHeight()*2);
               else {
                    return new Dimension(200, 200);
          public Dimension getMinimumSize() { return new Dimension(200, 200); }
          private MouseListener exitListener = new MouseAdapter() {
               public void mouseClicked(MouseEvent e) {
                    System.err.println(BubbleLabel.this.getBounds());
}

Similar Messages

  • HT201209 iTunes will not use the redeemed gift cards on my account, I have a $30 credit and when I try to purchase a song it goes right to my credit card on file. Why does this keep happening

    iTunes will not use the redeemed gift cards on my account, I have a $30 credit and when I try to purchase a song it goes right to my credit card on file. Why does this keep happening???

    Any time you've changed anything in your billing, it does this once to very things.

  • HP Photosmart C8180 Printer! WHY does this keep happening every day??

    I have only had this for 3 months and it already has problems.
    It keeps telling me its out of paper when it is not.
    i always have at least 20 sheets in there!
    You can hear the rollers going but it can't pick up the paper and I only use high quality A4 paper in there.
    i then have to pull the tray out and push it back in, and yes i have the paper inserted in there correctly
    also, sometimes when i get this "out of paper" message, i ignore it and just press OK and it works fine 
    why does this keep happening?
    this is disgusting coming from a Quality brand like HP
    think its time to go to BBC Watchdog! 
    A printer is an item meant to print. 
    It is generally helpful if a printer recognizes such out-of-the-ordinary, eccentric, unheard-of media such as...oh, I dunno, 8.5 x 11-inch PAPER?????
    It claims repeatedly to have run out of paper. No paper. No paper. Insert paper into paper tray. Now, granted, the minimalist quality of the paper tray--it holds 20 pages, roughly--might convince you that I had indeed used up all my paper; this is not the case. 18 of the 20 sheets are still there. So I readjust that paper, close the tray. It starts to pull in a piece of paper, and then there is the giant crunchy noise of a paper jam in progress. And forget about “easy access” for removing them, either.
    In the months I have had this printer, I don’t believe it has EVER allowed me to print five pages consecutively without some sort of problem.  To me, this is known as an EPIC FAIL. 
    Message Edited by Waynester on 04-16-2009 04:09 PM

    So how is the printer set up?  Is it wireless or USB?  If USB you will need a cable, purchased seperately.  It is a standard A/B USB cable widely available inexpensively.  (The $1 cables form the dollar store work fine....
    Running the diagnostics at http://www.hp.com/go/tools may help resolve the issue.
    Bob Headrick,  HP Expert
    I am not an employee of HP, I am a volunteer posting here on my own time.
    If your problem is solved please click the "Accept as Solution" button ------------V
    If my answer was helpful please click the "Thumbs Up" to say "Thank You"--V

  • HT1848 How do I sync my music on my computer to my iPhone - why does this not happen automatically when I connect?

    How do I sync my music on my computer to my iPhone - why does this not happen automatically when I connect?

    Do you have iTunes set to sync music to the device?
    Have you read the User's Guide that explains how to use the device?
    Syncing media and content to iDevices

  • My firefox Freezes randomly! I'll be working on the website for 2, 5 or 15 minutes. Then i'll click in the page to get to the next page, and it will just freeze! I already tried removing the "preloading" feature, so why does this keep happening?

    My firefox Freezes randomly! I'll be working on the website for 15 minutes, (google places, yahoo mail). Then i'll click in the page to get to the next page, and it will just freeze! I already tried removing the "preloading" feature, so why doesn't this keep happening?
    My firefox at home, (version 3) does not have this happen! I'm afraid of upgrading to version 3 because of all these problems. I use FireFox for work so i really need it and I'm wasting crucial time restarting websites and updating my websites/blog/business listings from scratch. not right!
    I also notice it happens a lot to Harley Davidson website.

    freezing at regular intervals:
    :http://blog.bonardo.net/2011/09/30/is-your-firefor-freezing-at-regular-intervals
    : https://addons.mozilla.org/firefox/addon/places-maintenance/
    :<br>Install add-on, run at least the option mentioned in the article, I ran them all. When finished you can uninstall the extension, all without taking taking Firefox down, The extension is one of the new JetPack extensions. (Firefox 8 --Nov 8, 2011-- should not have this particular problem).

  • TS4148 My iphone 4 has been updated to the newest version, but i constantly tells me that there is no SIM card installed. why does this keep happening?

    I have restarted my phone numereous times (because there's nothing else you can do to an iPhone) and every time it turns back on it'll have bars for a little while and then say " No SIM installed"  or it'll go straight to "No SIM".  Why is this happeneing and how can i fix it?

    Sounds like your iPhone was hacked/modified/jailbroken to work
    with wireless carrier other than the one it was purchased from. The
    update has relocked it to the original carrier. Contact the original
    carrier to see if they offer unlocking and if you qualify - only the
    carrier to which the iPhone is locked can unlock it.
    What does it say when you look at Settings=>General=>Carrier?
    Be advised that the previous modifications to change from original carrier
    to your local Carrier may have rendered the software unable to be updated or
    officially unlocked.

  • Why does this keep happening?

    I have currently downloaded Skype on my iPad, as I have no laptop which allows me to use it. I also have an iPhone which I have Skype downloaded onto for when I'm on the go. My problem now is that my contacts won't show online. I have the latest version of Skype and also the latest version of iOS. When I used the application yesterday they were showing up fine, but I have logged in today and their pictures won't show it is just a blank picture with a question mark and also some of them are appearing offline when they are online. Certain contacts are online with no picture and their username but not their actual name. I have checked on my phone and it shows they are online, but with no picture and their usernames only. I have tried logging out and logging back in, I have tried going offline and back online, I have uninstalled the app and reinstalled it, I have also deleted them and added them again but nothing has worked. When I message the offline contacts my messages aren't getting through. This has happened twice now and it's really starting to annoy me as I need to keep in contact with them over personal and important matters. Can somebody please fix this? It seems like nobody is bothering to update or fix the bugs on the iPad and iPhone apps lately.

    I thought I was the only one with this problem! With my first iPod it happened everytime it would recieve any sort of small bump or shake. I don't mean a drop, just a small tap. Sometimes it would lose info if I ran up or down the stairs and my (otherwise empty)jacket pocket would shake with it in there. Checked/unchecked all the tabs, reset it, updated it...nothing. The only thing that would work was to delete everything and reload it.
    After looking online and finding no help, finally took it back the the Apple store and after looking at it they just switched it out(with a refurb). Which kinda ****** me off cause basically in the end I basically paid full price for a refurbished ipod.
    Anyways my second ipod isnt as touchy but so far in the three weeks I've had it it's done it twice(the first week I didn't use it cause I was P.O'ed about getting a refurb considered trying to take back).Out of the blue this time, no outside source needed. If/when it happens again I'm just taking it back.
    If any of you iPod guru's out out there know of a (good,permanant)fix please post it! I'd rather not deal with the store.
    Just a note: Don't think I abuse the ipod at all. I'm actually rather anal about it. No drops, not a scratch on it.I probably treat it better than I treat my kids.
    Good luck Justin! You are not alone!!

  • Song appear in iTunes, BUT not on my ipod Touch. Why does this keep happening?

    This is about the 4th time that i've had this issue. My songs/playlists appear in iTunes when I connect my iPod Touch, BUT the songs don't show on my iPod.
    Any suggestion on how to fix this or why it keeps happening?

    There's a special iTunes forum where you'd get a lot of readers who specialize in iTunes issues.

  • Whenever I click on a song in my itunes library an exclamation point appears and I am no longer able to play this song or video why does this keep happening and what can I do to fix it?

    Whenever I click on a song or video in my library and I try to play it, and exclamation point immediately pops up and it tells me that my song or video's origional file cannot be located. It has happened to over 100 of my songs and I would like to know what is happening and what I can do to fix it. Let me know. Thanks!

    The usual explanation for this is that:
    1. You have changed the iTunes preferences so that when importing a song the file is not copied into the iTunes media library - doing so is the default.
    2. You have subsequently moved the original file, which iTunes has been using to play your song, and so of course it's lost contact with it.
    If 1. is not the case, then the files in the iTunes Library (by default, in (user)/Music/iTunes/iTunes Music) may have been moved, deleted or become corrupted. You should check in that library, but don't start moving files in there about. If this is the case you should delete the songs in the iTunes Music list, not in the Finder, and re-import.

  • I plugged in my itouch and itunes says there's an error and tells me to restore to factory mode.WHY does this keep happening to me?

    Okay so before my itouch was jailbroken then all of a sudden it deleted all my songs and when I plugged it back into the computer itunes didn't recognize it so I had to restore it to factory settings deleting my 20+ apps . After I did that I jailbroke it again since the hardware was basically brand new, then while it was syncing i transfered a song and it interfered with the sync and deleted everything so I upgraded it once again. Now I have't jailbroken it and it the same thing has happened TWICE. Everything is fine and I plug it in and my computer recognizes it cause its charging but Itunes says there's and error and it simply doesn't recognize it and makes me restore it to factory settings DELETING everything. Now I'm scared to buy apps because if this happens again it deleted everything thousands of songs I have to put back manually etc. What is wrong with my itouch? Is it the itouch or the itunes because my itouch is no longer jailbroken and working fine. I took it to the apple store and they told me they couldn't do anything about it because it was working fine on their computer. -_- HELP?!!! I'M tired of this happening.

    brendan.blaine23,
    which version of iTunes is currently installed on your MacBook Pro?

  • Why does this keep happeni

    Long ago... like a couple months ago, my player used to start flashing once I turned it off. And sometimes my desktop wouldn't recognize it. I sent it in for a replacement and BAM I was happy. I treated it like gold. Pure gold.
    The other day I go to turn it on and, oh look, it freezes on the Creative logo. So, I perform a clean up and reboot it. Still froze. So I go one step further and format it. Still froze.
    I figure, let me email Customer Support and they are no help at all. Primarily because my initial warranty expired so now i have to pay for help.
    Now, not only does it freeze on the Creative logo, the trademark information is stuck there too, the lights (OLED, I believe) DO NOT turn on, and it is not recognized by my computer.
    Please tell me someone else had this problem and it was magically solved... I really do not want to end up having my mom regret buying me this $200 emotional mp3 player. =/

    Usually that error indicates a drive malfunction; specifically, the drive is spinning down and not responding to bus signals. Some "Eco" or "green" drives are known for this behavior. The following steps may help:
    From the menu bar, select
     ▹ System Preferences ▹ Energy Saver ▹ Power Adapter
    and uncheck the box labeled Put the hard disk(s) to sleep when possible, if it's checked.
    If the drive is connected to a hub, connect it to a built-in port on the computer.
    If a firmware update is available for the drive, apply it.
    Contact the drive manufacturer to see whether there's a firmware setting you can change.
    If you installed vendor software for the drive, uninstall it.
    If none of the above steps resolves the issue, try another drive.

  • WHenever I update all apps, apple has me reset SOMETHING on my account.  Why does this always happen?

    Every time I update my apps, apple forces me to reset a password, or re-enter my credit security number, or just SOMETHING.  Is there any way to set a password, give my credit card and just have it stay that for more than one week?

    This is also happening to me every week and I guess there is no solution to it as no one has replied to me either.
    Shelly

  • I keep getting the message to contact the iTunes store when I try to make a purchase.  Why does this always happen?

    I keep getting the message to contact iTunes support when I try to make a purchase, and I can't log in to see my purchase history.  I also think that when I get this error message, my account is still getting billed. How do I fix this problem?

    Gramma56 wrote:
    ...  How do I fix this problem?
    Contact iTunes Support as requested...
    http://www.apple.com/support/itunes/contact.html

  • The message that comes up says that the server can not be found ...why does this keep happening?

    I continually get the message that the
    'server can not be found at this address. Check to make sure that the address is typed properly etc. etc.'
    When I try to use Internet Explorer with the same info there is no such message. Why

    A possible cause is security software (firewall) that blocks or restricts Firefox or the plugin-container process without informing you, possibly after detecting changes (update) to the Firefox program.
    Remove all rules for Firefox from the permissions list in the firewall and let your firewall ask again for permission to get full unrestricted access to internet for Firefox and the plugin-container process and the updater process.
    See:
    *https://support.mozilla.com/kb/Server+not+found
    *https://support.mozilla.com/kb/Firewalls

  • Every time I open my iTunes - my library is gone. Why does this keep happening?

    Hey guys,
    The folder with all my music in it is located on my desktop. I've had it like this for years now with never a problem.
    Up until the most recent update, my library is gone everytime I open my iTunes.
    Thankfully I saved my playlists to text documents, but it is becoming an enormous bother now to keep re-adding them.
    I've searched the forums to no avail - anyone have any advice for me?
    Much Appreciated,
    Andrew

    Just want to share my fix for this...... Don't know that computer you are dealing with but if sony, here it is
    WOW! Thanks to all who directed me to Sony for this issue. I have downloaded the update http://support.apple.com/kb/TS2715 (which by the way would not run for the first few times stating it was an update for Vista even though I chose the Windows 7 OS and the page showed was for 7.) I have rebooted about 4 times so far and everything is still in iTunes. Oh thank you all.... BTW I had my computer in with the Sony Backstage guys for a tune up a few months ago and I explained this issue to them. They had no idea and recommended I go over to the Apple store in the Mall. I would think they should be versed on various software related issues which can create trouble for users of their products just as they are versed in the nuts and bolts of how to save this, and move that, and make backup disks, and read my email. : ) Keeping my fingers crossed.
    All this technology conflict.... Can't we all just get along???

Maybe you are looking for

  • Speeding up the use of Pen Tool in connection with Audio Keyframes

    I remember that one of the editing systems that I used to work on (either Premiere, Avid, or DPS) had this nifty little button that automatically generated three audio keyframes with the middle keyframe at -inf dB. It was great for getting rid of mic

  • Sudden problem with iTunes quitting - problem and solution

    This is a fairly lengthy diatribe but it was driving me nuts and so hopefully will help someone else: The Problem: I have an XPS M1710 running Windows Vista. A couple of days ago all Apple programs started to malfunction, specifically iTunes, QuickTi

  • Error Stack Alerting

    Good morning, Within BI7 data staging to Infocubes. I have a requirement to generate an email alert where records have been sent to the Error Stack,  to negate the need to check DTP logs.  I acknowledge the process chain has message handling, but thi

  • Can I install App Server 10g (10.1.2) on Solaris 10 Operating System

    Hi, I have to install Application Server on Solaris 10 (SPARC) and I have the Setup of AS 10g 10.1.2. So,Can I install this AS on my system. Also I have search for this on OTN and find that AS 10.1.3 is the version that can be used but its installati

  • Production Order creation through Tcode- CO10.

    Hi, Can I restrict new Production Order creation through Tcode- CO10 unless previous order is Techoed / closed. Issue : Users having authorisation for CO10, are creating multiple orders without taking them to logical closure. Since budget is getting