Why does Null restrict my movement?

With the help of these forums I was able to place JLabels with the use of frame.getContentPane().setLayout(null); The problem I'm having now is that the JLabel (whose image path is penguin.gif) can move around in all directions except down. Can anyone help me fix this?
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PenguinWars extends JFrame implements KeyListener {
     public boolean left = false, right = false, up = false, down =false;
     private static boolean start = false, end = false;
     public static int w = 300, h = 500, x = 200, y = 520, xw = 20, xh = 25; //w,h for frame; x,y for penguin position, xw, xh for penguin size
     private static int startLabX=200;
     private static int startLabY=520;
     private JLabel example=new JLabel();
     private static JLabel lab;
  public PenguinWars() {
    // Create a MovingMessagePanel for displaying a moving message
    add(new MovingMessagePanel("O", "X"));
    example.setSize(20,25);
    example.setLocation(0,0);
    example.setBackground(Color.black);
    add(example);
  public void keyControl() {
         if (0 < x) {
             if (left) {
                 x -= 3;
         if (w > x + xw) {
             if (right) {
                 x += 3;
         if (25 < y) {
             if (up) {
                 y -= 3;
         if (h > y + xh) {
             if (down) {
                 y += 3;
   public void keyPressed(KeyEvent ke) {
      switch (ke.getKeyCode()) {
             case KeyEvent.VK_LEFT:
                 if (-186 < startLabX) {
                 left = true;
                startLabX-=5;
                 else
                     left = false;
          lab.setLocation(startLabX,startLabY);
                 break;
             case KeyEvent.VK_RIGHT:
                 if (186 > startLabX) {
                 right = true;
                 startLabX+=5;
                 else
                     right = false;
          lab.setLocation(startLabX,startLabY);
                 break;
             case KeyEvent.VK_UP:
                 if ( -550< startLabY){
                 up = true;
                 startLabY-=5;
                 else
                     up =false;
          lab.setLocation(startLabX,startLabY);
                 break;
             case KeyEvent.VK_DOWN:
                 if (0 > startLabY) {
                 down = true;
                 startLabY+=5;
                 else
                     down = false;
          lab.setLocation(startLabX,startLabY);
                 break;
          /*     case KeyEvent.VK_ENTER:
                start = true;
                end = false;
                break;
     public void keyReleased(KeyEvent ke) {
         switch (ke.getKeyCode()) {
             case KeyEvent.VK_LEFT:
                 left = false;
                 break;
             case KeyEvent.VK_RIGHT:
                 right = false;
                 break;
             case KeyEvent.VK_UP:
                 up = false;
                 break;
             case KeyEvent.VK_DOWN:
                 down = false;
                 break;
     public void keyTyped(KeyEvent ke) {
  /** Main method */
  public static void main(String[] args) {
    PenguinWars frame = new PenguinWars();
    int optionType = JOptionPane.YES_NO_OPTION; // YES+NO+CANCEL
    int messageType = JOptionPane.QUESTION_MESSAGE; // no standard icon
    int res = JOptionPane.showConfirmDialog(null, "Welcome to Penguin Wars!\n"+
            "How To Play The Game: \n"+
            "You can begin the game by pressing the SPACE BAR. \n"+
            "The goal of this game if to save our penguin from the garbages that are contaminating its environment.  \n"+
            "Move the penguin using the arrow keys to avoid all the garbages. \n"+
            "The game will be over when the penguin eats too much garbages. \n"+
            "You can earn points by feeding healthy fish to the penguin. \n", "Directions",
                                        optionType, messageType);
    if (res == JOptionPane.NO_OPTION) {
        System.exit(0);
    if (res == JOptionPane.CLOSED_OPTION) {
        System.exit(0);
    *lab=new JLabel();*
    *lab.setSize(25,25);*
    *lab.setLocation(startLabX, startLabY);*
    *lab.setIcon(new ImageIcon("penguin.gif"));*
    frame.setTitle("Penguin Wars");
    frame.getContentPane().setLayout(null);
    frame.getContentPane().add(lab);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 600);
    frame.setLocation(200, 100);
    frame.addKeyListener(new PenguinWars());
    frame.setVisible(true);
    ImageIcon icon = new ImageIcon("garbage.gif");
     // allocate array for enemy labels
     JLabel[] enemies = new JLabel[5];
     // all elements of this array are null, not instantiated
     // initialize the array by instantiating the elements
     for(int i = 0; i < enemies.length; i++)
      int en_posx = (int)(Math.random()*300)+1;;
      int en_posy = 0;
    enemies=new JLabel();
enemies[i].setSize(25,25);
enemies[i].setLocation(en_posx,en_posy);
enemies[i].setIcon(new ImageIcon("garbage.gif"));
frame.getContentPane().add(enemies[i]);
     } //end for
//setting background image
Color background = new Color(150,100,255);
Container con = frame.getContentPane();
con.setBackground( background );

Your code is too large and won't compile. Your best bet is to try to solve your problem with a very simple class -- one that does nothing but moves a simple JLabel around a JPanel, one that has no extraneous dependencies, such as "MovingMessagePanel" or other classes. This way if the code still fails, you can post it here, we can more easily understand it and actually try it out, and we can more easily help provide you with a solution. This is called creating an SSCCE (please see the link).
edit: you may have a solution above by tjacobs, but I still stand by my recommendations, if not for this thread then for future threads.
edit 2: You should seriously consider using key bindings and not a key listener.
edit 3: You never replied to my post in your most recent thread: [http://forums.sun.com/thread.jspa?threadID=5419871&messageID=10885069#10885069]
By responding and acknowledging, you'll encourage folks to help you in the future. Just fyi.
Edited by: Encephalopathic on Dec 13, 2009 10:59 AM
Edited by: Encephalopathic on Dec 13, 2009 11:00 AM

Similar Messages

  • Why does it take I movie 6 hours to produce thumbnail for a new project

    why does it take I movie 6 hours to produce thumbnail for a new project

    Hi
    Seems very long time.
    When my Mac starts to get into a slow-motion in action eg encoding DVDs or alike - it's nearly always due to that free space on Start-Up (Mac OS) hard disk is to low.
    • I try to never have less than 25Gb free space
    • 10Gb - might work but slows down
    • 5Gb - slow and instable
    • less - incredibly slow, instable and if DVD is produced - it usually doesn't work
    This space can not be utilized on other hard disks - Neither for Mac OS or iMovie or iDVDs temp. files - Has to be stored here. No-where else.
    Yours Bengt W

  • Why does the page not move smothe when i scroll?

    Why does the page not move smothe when i scroll?
    Sometimes it even move slower then i Scroll?
    I use a Mac and i have tried to reinstall the program.

    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Appearance/Themes).
    * Don't make any changes on the Safe mode start window.
    In Firefox 4 [http://kb.mozillazine.org/Safe_mode Safe mode] disables extensions and disables hardware acceleration.
    * Tools > Options > Advanced > General > Browsing: "Use hardware acceleration when available"
    See:
    * [[Troubleshooting extensions and themes]]

  • Why does iTunes freeze when movie download is processing and it will not restart the download but yet it billed my acct for payment already?

    Why does iTunes freeze when movie download is processing and it will not restart the download but yet it billed my acct for payment already? It has been a week now and still not done processing. I get an error message when I try to restart the download.

    What Windows version?

  • Why does my tool box move up so I can not use it?

    WHY DOES MY TOOL BOX ALL OF A SUDDEN TODAY MOVE UP SO i CAN NOT SEE IT OR USE IT? ALSO i CAN NOT SEE MY BOTTOM TOOL BOX EITHER. WHAT CAN i DO TO CHANGE IT BACK OR DO YOU HAVE TO?

    Hit '''F11''', as you might have enabled the Full Screen mode.

  • Why does exporting a quicktime movie take so long?

    I'm exporting an 88-minute-long HDV movie as a self-contained quicktime without recompressing. The media is all on one ESATA drive and the target disk is a second ESATA drive. It takes five hours and uses >150% of my CPU during the export. It seems to me like it shouldn't take nearly that long, nor should it use so much CPU since basically all it's doing is copying data from one disk to another, right? Any idea why it's taking so long and using so much CPU? Thanks.

    No, wrong. It is creating a completely new GOP structure for your MPEG2 based edit.
    Ah.
    This is one of the drawbacks of working/delivering in HDV ... With that in mind, is there any special reason you are creating an HDV self contained master?
    I'm making it self contained so I can put the whole thing on my MBP's internal hard drive and show it to people without having to carry terabytes of media around. I'm staying in HDV because I started out working in Final Cut Express, which converts everything to AIC, and had very bad results: my media files grew by a factor of three, everything was ridiculously slow, and my machine crashed regularly, particularly during captures, which was unbelievably frustrating because that meant I had to babysit the machine throughout the entire capture process (and often through multiple iterations of the capture process interleaved with machine reboots). In fact, the only reason I started using FCP instead of FCE is so I wouldn't have to transcode.

  • Why does my 40 minute movie become a 7 hour video in compressor?

    I've made a final cut HD movie about 41 minutes in length.  When I send it to compressor I have to wait many hours while Compressor does it's magic.  The reason for the unreasonable time is that it is compressing a 7 hour plus file rather then the 40 minute movie sent to Compressor.  When the compressed file is sent to DVD Studio Pro I have to drag a 7 hour timeline down to 40 minutes of actual video/audio files.  In Final Cut the sequence time line is only 40 minutes long and I can not find why this relatively short movie becomes so long when dispatched to Compressor.  Any solutions?

    Open your project and hit Shift Z. See whether there is any file beyond 40 minutes on the Time Line,
    Take the Range tool and do a selection around your movie in the Time Line, In Share, choose Master File and save.
    Open that file in Quick Time and it will be 40 minutes. Bring that file into Compressor for whatever encoding job you need.
    Good luck.
    Riss

  • Why does quicktime 7 save movies to grapher movies?

    Installed the latest quicktime  7.6.6. Have the pro key.
    When I save a movie as a self-contained movie, it saves it as a grapher movie. When I open this movie, it opens in grapher and I can only play it, not crop it for instance. And if I open it in Quicktime it's the same problem.
    Can I simply get rid of the Grapher software as I don't think I will ever need it?
    Did I miss something in this new version of Quicktime?
    In previous versions I would just go  to 'save as' and it was quick and easy – files saved as quicktime movies (.mov).
    Appreciate your insight.

    It does NOT have a new screen option, JUST a NEW MOVIE option...
    there are eons of complaints about this.. on this thread
    She cannot record my image..She just has NEW MOVIE OPTION.. We were online for one hour.
    I had NEW SCREEN option on my Mac osx 10.6
    she was forced to buy quick time 7 pro and it does NOT give her NEW SCREEN option.. absolutely NOT

  • Why does WL7 restrict security deployment descriptors?

    Hi,
    WL7 has nice role based features - I can create a role based on
    username/groupname and time.
    However, when you define a role for a web application say, in a BEA specific
    file weblogic.xml,
    then I can only do this:
    <security-role-assignment>
    <role-name>RoleA</role-name>
    <principal-name>SomeName</principal-name>
    </security-role-assignment>
    Why is this so restrictive? How can I add a time based component to this
    role for instance?
    Do I have to use the Admin Console? If I do use the console, then I can't
    persist my changes, so in effect I can't use all the role features.....
    I expected to find something like:
    <security-role-assignment>
    <role-name>RoleA</role-name>
    <constraints>
    <and>
    <principal-name>SomeName</principal-name>
    <group-name> Foobar </group-name>
    </and>
    <or>
    <time> xxxyyxxx</time>
    </or>
    </constraints>
    </security-role-assignment>
    or something similar :-)
    Regards,
    Jon

    The iAS registry is stored in a flat file (reg.dat) on UNIX platforms.
    David
    Raymond Brandon wrote:
    And probably now a stupid question:
    I'm wondering why IAS needs the GUIDs (global unique identifiers) to
    register EJB's when it uses JNDI to look them up?
    I'm using windows NT and can see the GUIDs in the registry under iPlanet
    Application Server, but I wonder how this is done on platforms that don't
    have a registry like Unix?
    Raymond

  • Why does iTunes offer most movies for purchase rather for rental?

    Maybe there is no answer for this question.  Apple must desparately want me to use any service other than iTunes.  Why the F would I want to be the proud owner of "Place Beyond the Pines"?  So I can watch it again and again?  Nearly everything I want to watch is for sale for like 15$.  Forget it.  Sorry for the rant.
    How can I communicate to iTunes the magnitude of my distaste for their movies offering?

    It's not Apple's choice, it's the film studios that set whether a film is available for renting and/or buying.
    You can try requesting that a particular film is offered as a rental, but without the studio's agreement it can't happen : http://www.apple.com/feedback/itunes.html

  • Why does Pages restrict me to two pages?

    I have recently bought a Mac Pro and am trying to get used to Pages. If I am doing multiple page documents, I keep finding that after two pages, I seem to lose extra pages, although they are still there if I look back to previous versions. Any idea why this is happening, and what I can do to stop it, please?

    Sounds like you have floating images with wrap on them and are using spaces, returns and tabs to push objects around.
    Pages has a particular way of working with pages.
    In Word Processing documents Pages creates or eliminates pages based on whether there is anything in the main text layer ie the area between the page margins.
    If there is more text than fits on a page, a new page is created and the text flows onto that.
    Conversely if you eliminate text so that there is no more text on the current page, the pages shrink back.
    This includes inline objects (things pasted into the text) which act just text, in fact like big fat characters.
    If you have floating images that are not part of the flow of text, they stay put on the page where you created them. If that page has been eliminated when the text was reduced, the image remains where it was on the no longer visible page.
    If you create some more pages by Menu > Insert > Page Break those images or objects will be visible once more.
    In your case I suggest you have a muddled set of floating objects and lots of spaces and returns just to push things in place. The combination of the text wrap from the objects and all those invisible characters can make things pop unexpectedly.
    1. Menu > View > Show Invisibles
    2. Get rid of all the spaces and returns other than just the one after each paragraph or word
    3. Menu > Insert > Page Breaks until you see all your objects again
    4. Cut and paste those where you want them in the text.
    5. Use floating objects when you get a better hang of layout
    Peter

  • Why does my imported .mp4 movie appear black?

    Imported an .mp4 movie (technical animation created in another app) into EA (2014 CC).
    Added buttons and interactivity, everything works fine, assignment completed.
    A month later, go back into EA to make minor changes.
    However, when I'm EA, the .mp4 movie now appears black, thus making it impossible for me to make changes.
    FYI:  When I Preview In Browser, the animation plays back fine.
    Question: Any ideas as to why the imported movie now appears black when I play it back within the app?

    Joe,
    ·         I just uploaded the folder to my “Creative Cloud Files”.
    ·         Right now, it is set to “Share with Nobody”.
    ·         When I click on “Share with”, I get 2 choices, “Nobody” or “Specific people”.
    ·         When I click on “Specific people”, I get 2 choices, “Everyone” or “Find people”.
    ·         I’d rather not select “Everyone” because it is a company doc.
    ·         Is there a way for me to add your name in “Specific people”?
    ·         Please advise, thanks.
    Eddie
    Eddie Ostrowski
    Pitney Bowes Inc. | Multimedia Specialist
    Global Knowledge and Content Management
    37 Executive Drive | Danbury, CT  06810 USA
    Internal:  8.796.6691 | External:  203.796.6691

  • Why does the nav bar move in a browser??

    Please help!  In dreamweaver the nav bar looks perfect and is over the top of the blue line under the picture header but when I put it in a browser, it moves as you can see from my link!!
    test site
    Please can anyone tell me why??  I have a feeling it will be a CSS positioning thing but I am very very new to this so do not know how to rectify!
    Thanks if you can help!

    Look this is not a good solution, it just hacks around the issue.
    Add this to the css style:
    #header p {
    padding: 60px 0 0 0;
    margin: 0;
    Then you need to go into code view and change these code lines:
    <div id="container">
      <div id="header"><br >
        <p align="right"><br >Complete Energy Certificates Ltd </p>
        <p align="right">&nbsp;<br><br >
        </p>
        <div align="center">
    To this:
    <div id="container">
      <div id="header">
    <p align="right">Complete Energy Certificates Ltd </p>
        <div align="center" style="margin-top: 71px;">
    Now let me explain. You're trying to position elements using <br> tags which will not work. The solution I provided is a sticking plaster one and may fail in some browsers because it still relies on guess work.
    A far better option would be to rebuild that top section of your page into a solid structure.
    A <div> which contains the grass bank and sky image but NOT the blue line that your navigation sits on. You can set this <divs> height to the height of the image and then include your text 'Complete Energy Certificates Ltd' within it.
    Like:
    <div id="header">
    <p>Complete Energy Certificates Ltd</p>
    </div><!-- we close the header -->
    Now set some css:
    .twoColElsLtHdr #header {
    background-color: #FFF;
    background-image: url(images/header2.jpg);
    background-repeat: no-repeat;
    background-position: center;
    font-size: 12px;
    height: 205px; /* make the height the same as that of the background image */
    Move your 'Complete Energy Certificates Ltd' text into position by setting some top
    and right padding on the paragraph tag:
    .twoColElsLtHdr #header p {
    margin: 0;
    padding: 60px 10px 0 0;/*top,right,bottom,left*/
    text-align: right;
    Next introduce a navigation <div> right after the 'header' <div> and put all the table code relating to yuor menu in it:
    <div id="header">
    <p>Complete Energy Certificates Ltd</p>
    </div><!-- we close the header -->
    <div id="navigation">
    <!-- all table code for navigation goes here -->
    </div><!-- we close the navigation -->
    Style your naviagtion <div> to have a blue background that matches the menu images:
    #navigation {
    background-color: #XXX;
    Think of contruction as simple building blocks.

  • Why does my just rented movie say I can play it in 48 hours?

    So we came home on a Friday Night and commenced our family Pizza and Movie Night, sat down covered with cheese and for the first time decided to rent a movie on the Apple TV.  We had watched NetFlix movies for almost a year, with no issues.  But... now my boys wanted to watch Transformers 3... we'll have to rent that.  No problem!  Apple TV has us covered.  Rent, play, keep eating.  Not so much.  The spinning "thinggy," as I the 7 year old calls it, greeted us with a message we couldn't believe.  "Your movie will be ready to play in 48 hours and 26 minutes."
    You can imagine our house was not a pleasant place to be...
    So, is this normal?  Is the vaunted Apple TV rental system not a streaming service?
    Jayden (the 7 year old) sends..

    Sounds like this is indicative of the Apple TV not getting a good connection from which to stream... that is, data is trickling in.
    If the rest of your Internet connectivity appears to be OK (you can browse around in the iTunes Store, watch YouTube videos, examine people's Flickr photos, etc.) then the only thing left is that Apple's TV rental services are in a slump.  I suggest you contact the iTunes Store support channels and tell them what you are experiencing.
    The URL for iTunes Store support is:
    https://expresslane.apple.com/GetproductgroupList.do
    for the United States.  Of course, if you are not in the United States, use the support channels appropriate for your country by using this link:
    https://expresslane.apple.com/GetCountriesDetails.do
    Good luck!
    —tonza

  • Why does only the first movement of a symphony play?

    I have all of Mahler's symphonies on Itunes. I try to play them on my Ipod and the first movement of each symphony plays and then it shuts off as if the album is done. Any ideas what I did in loading these CDs onto Itunes that could cause this?
    In case you're wondering:
    Each symphony is listed as an album, with each movement as a track of that album. The disk of symphony #1 says "disk 1 of 13". Part of a compliation: No. Include when shuffling: No.
    Thanks for any help.

    The Apple guy told me yesterday that you have to RECORD it first.
    Start from the first slide and go thru all of them.
    Then they will playback.

Maybe you are looking for

  • Moving tables with data from one client to another

    Hello friends I have 2 clients 001 and 002. I have created a table with lots of data on client 001. I have to get the same table on 002 also with the same data. Is there an easier way of transfering this data from one table to another? I would apprec

  • MiniDisplayPort to RCA... Doesn't Exist! Options??

    I have a MBP Unibody and a projector with RCA in. I'd like to go from my MBP to the proj., but currently there is no MDP (minidisplayport) to RCA. Super annoying. Would the next advisable option be MDP --> DVI (or VGA) --> RCA? Which would throughput

  • Aggregation in BEx query

    Hi Gurus, I am stuck in a peculiar problem. I would try to explain with the scenario. The below is how I get the data from our cube to my Bex query Date                PO Number    PO Line Item    PO Count     PO Line Item Count 01.01.2011     X1    

  • FXS MGCP issue after upgrade to UCCM 7.X

    We have an fxs port registered with ccm via an mgcp gw (2811), we recently upgraded the Cluster from 5.1(3g) to 7.1(2b) and now the port is registered but it can't make any calls.  When you dial an extension the extension rings but then stops and you

  • How to save documents in their original format?

    Hi, we have the problem that we have to save and archive received documents at the adapter engine in their original format, p.e. EDIFACT- or RosettaNet-documents in their original EDIFACT- or RosettaNet-format. Is it possible to save the documents at