JButton keeps JFrame from succesfully implementing KeyListener?!

Look at this code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame implements KeyListener
     private JButton myButton;
     public Test()
          Container c = getContentPane();
          c.setLayout( new FlowLayout() );
          myButton = new JButton();
          myButton.setEnabled( true );
          c.add( myButton );
          addKeyListener( this );
          setSize( 100, 100 );
          show();
     public void keyPressed( KeyEvent e )
            System.out.println( "keyPressed" );
     public void keyReleased( KeyEvent e )
          System.out.println( "keyReleased" );
     public void keyTyped( KeyEvent e )
          System.out.println( "keyTyped" );
     public static void main( String args[] )
          Test window = new Test();
}When you execute this program, the JFrame does not resolve keystrokes. It should though, because it implements KeyListener and overrides all required methods. But here is the strange thing: Try changing
myButton.setEnabled( true );to
myButton.setEnabled( false );Now the JFrame is able to respond to keystrokes by executing the proper methods! But what use is a button if it is not enabled. I need my buttons in the JFrame, but I also need the JFrame to respond to the keystrokes.
Anyone know about this problem and how to solve it??
Thank you!

?? Say you want to make a small game. A square is drawn onto the frame. The user presses the up button on the keybord and the square 'moves' up (it is repainted at a different coordinate). But the user also needs to be able to (re)start the game and exit through the use of JButtons. That is the purpose and the problem is stated in my first post...
Anyone else has an idea?
thx

Similar Messages

  • Can not add a picture to the JFrame from an ActionListener class

    As topic says, I can not add a picture to the JFrame from an ActionListener class which is a class inside the JFrame class.
    I have a Map.java class where I load an image with ImageIcon chosen with JFileChooser.
    I my window class (main class), I have following:
    class OpenImage_Listener implements ActionListener
         public void actionPerformed(ActionEvent e)
              int ans = open.showOpenDialog(MainProgram.this);     // "open" is the JFileChooser reference
              if(ans == open.APPROVE_OPTION)
                   File file = open.getSelectedFile();                    
                   MainProgram.this.add(new Map(file.getName()), BorderLayout.CENTER);     // this line does not work - it does not add the choosen picture on the window,
                            //but if I add the picture outside this listener class and inside the MainProgram constructor, the picture apperas, but then I cannot use the JFileChooser.
                            showMessageDialog(MainProgram.this, fil.getName() ,"It works", INFORMATION_MESSAGE);  // this popup works, and thereby the ActionListener also works.
    }So why can�t I add a picture to the window from the above listener class?

    The SSCCE:
    Ok, I think I solved it with the picture, but now I cannot add new components after adding the picture.
    Look at the comment in the actionlistener class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Test extends JFrame{
         JButton b = new JButton("Open");
         JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
         Picture pane;
         Test(){
              super("Main Program");
              setLayout(new BorderLayout());
              JPanel north = new JPanel();
              add(north, BorderLayout.NORTH);
              north.add(b);
              b.addActionListener(new Listener());
              setVisible(true);
              setSize(500,500);
              pane = new Picture("");
              add(pane, BorderLayout.CENTER);
         class Listener implements ActionListener {
              public void actionPerformed(ActionEvent e){
                   int ans = jfc.showOpenDialog(Test.this);
                   if(ans == jfc.APPROVE_OPTION)
                        File file = jfc.getSelectedFile();
                        Test.this.add(new Picture(file.getName()), BorderLayout.CENTER);
                        pane.add(new JButton("NEW BUTTON")); // Why does this button not appear on the window???
                        pane.repaint();
                        pane.revalidate();
         public static void main(String[] args)
              Test t = new Test();
    class Picture extends JPanel
         Image pic;
         String filename;
         Picture(String filename)
              setLayout(null);
              this.filename = filename;
              pic = Toolkit.getDefaultToolkit().getImage(filename);
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawImage(pic,0,0,getWidth(),getHeight(),this);
                revalidate();
    }

  • What's keeping me from buying the W540

    I have $$ to spend and no Lenovo to spend it on.  
    Here's what's keeping me from buying the W540:
    1) Physical buttons have been removed above the trackpad. 
    Many, many people complain about this in the W540 reviews:
    "Touchpad: I've commented elsewhere that this is the worse I've even seen. Absolutely useless. I've disabled both the touchpad and touchstick (again, useless) and just use a mouse."
    "I'd try the touchpad on the W540 for a while before you decide you can live with it, it is truly as bad as all the reviews say. I've disabled mine and use a mouse."
    "...two issues with the touch-pad. The first has to do with having to clunk the whole pad as opposed to tapping on a much smaller (and quieter) button. The second has to do with the touch pad activating when you are typing."
    Member "Bauden" provided an excellent rationale for why this feature change is wrong for Thinkpads:
    "For a MAC, a "click-pad" may work because the ENTIRE OS is designed to be used by a single mouse button. You CANNOT force this on PC users. On PC, right-click is used frequently for many essential functions, dragging and dropping and context menus . . . . the habit of using it has been ingrained into PC users by years of Microsoft tradition and applications (NOT APPS!)."
    I've used 10 Thinkpad laptops, I can't imagine being OK with that either.    Needing to use an external mouse is unacceptable.
    In fact, I'd bet the extra pressure needed to "tilt" or "clunk" the entire trackpad down to do the equivalent of pressing a gentle button from before will cause a greater frequency in RSI (Repetitive Stress Injury) in Thinkpad users.
    I do not see a single person who feel this feature removal/change is an improvement.
    Therefore, Lenovo, can you please change back?
    2) Bizzarre Resolution (2880 x 1620)
    I need / want UHD. I am thrilled that you are finally selling higher quality screens on your laptops.
    (Thank you Apple for putting that competitive pressure on laptop vendors.)
    Lenovo, please provide the resolution on the W540 that you have provided on the new Y50. (3840x2160)
    Why did you choose (2880 x 1620) resolution?
    1920 x 1080 isn't an even divisor of the native dimensions at full resolution, so resolving scaling issues by going to 1920x1080 would never look exactly right.
    But **please** Lenovo, keep the screen anti-glare.
    If you make above changes, please keep the following features:
    1) Anti-Glare screens
    2) Trackpoint
    3)  2 physical drive capability, 1 SSD + 1 other
    although it doesn't sound as easy as I'd prefer:
    "Thus, no matter what anyone tells you, you CANNOT buy a W-540 and think you will easily swap a DVD drive with, say, a second hard drive. It’s minor surgery, best done with a jeweler’s screwdriver and some fine needle nose pliers.
    Be sure to read the User Guide to keep from breaking the hatch cover. When I ordered mine, they shipped the Ultrabay carrier and the hard drive from the US, so they arrived early. I had to install them myself and found manipulating the tiny screws and pulling the hatch cover to be a bit scary.
    ……Not exactly what you would call “convenient.”
    from
    http://forums.lenovo.com/t5/W-Series-ThinkPad-Lapt​ops/LIVING-WITH-A-W-540/td-p/1528698
    4) Thunderbolt port
    And add back in the following features:
    I especially agree with these minuses in the "+/-" very detailed review by "Bauden"
    http://forums.lenovo.com/t5/W-Series-ThinkPad-Lapt​ops/LIVING-WITH-A-W-540/td-p/1528698/page/2
    = Missing drive indicator light
    Why in the world remove that. Please add that back in.
    = Missing bluetooth indicator light
    = USB 2.0 vs USB 3.0 ports can be easily identified with industry standard 'Blue' for USB 3.0.
    Why did you decide to not do that?
    After a couple hours of reading, I'd agree with the conclusion of Bauden when s/he said:
    "Overall a nice speedy machine, but that is not by Lenovo R&D.
    Intel, nVidia, and m.2 SATA are all wrapped in a container that is very poor when expecting a product labelled "Workstation". This is NOT a workstation among the items mentioned above and the wrong screen aspect ratio for photography / graphic applications."
    http://forums.lenovo.com/t5/W-Series-ThinkPad-Lapt​ops/LIVING-WITH-A-W-540/td-p/1528698/page/2
    Idea
    It seems like the team who designed the Lenovo Y50 did a great job for that machine's intended purpose.
    http://shop.lenovo.com/us/en/laptops/lenovo/y-seri​es/y50-uhd/
    (but is it really shipping in any quantity? Not a single user review posted to the community.)
    Maybe take the team who implemented the Y50 and have them design the new Thinkpad W550.

    Update:
    I'm glad those reasons above kept me from spending my own $ on this model since work ended out upgrading my old laptop.  Options were a W540 or a T440.  I had about 15 seconds to decide.  I went with the W540 tp get a larger screen. 
    Thoughts after several months: T
    Best thing on a day to day basis:  
    Overall, it's a screamer.  I can throw any workload at it and it doesn't flinch. 
    ( I7, 32gb memory, drive upgraded to a 1TB Samsung EVO SSD)
    Life is too short to wait on slow systems or slow hard drives.   This "best thing" overshadows everything else and makes me very happy with this system.  
    Worst thing on a day to day basis:  
    The keyboard layout. PageUp should be above PageDown.  Home should be above End. 
    Useless number key area. Why?  The NumLock key is right next to the Backspace key.  I'll accidentally toggle that Numlock key once a day or so when hitting backspace.  Then, the PageUp, Home, etc., keys on that keypad are useless and unpredictable.
    Mildly annoying:  
    1) The mousepad, for reasons described above.  Its tolerable but not great.
    2) The new DVD button location.  I accidentally open it twice a week when picking up / putting down the W540, and I've *never* used that silly DVD player.
    3) The "B" key, the key that's directly down from the red Thinkpoint tip, isn't right.  It doesn't press down cleanly.  bbbbbbbbbbbb   It's like it gets hung up on the red nibbet.

  • Keep gmail from synchronizing, storing mail or addresses

    How (in real detail) do I keep gmail from synchronizing or storing any mail, anywhere up in my new gmail account (including 'All Mail'), once it is downloaded to Thunderbird. I also do not want Gmail to store any addresses.
    I have TB version 24.4.0 /// I am using Windows.
    I can't find anything that applies to my situation (or I don't understand it). I've also read all the detail in TB support.
    I can't delete the email up on Gmail without it deleting it down in TB.
    (Once I implement the fix, can I then wipe all email up on the Gmail site without anything happening to TB - or is there something 'unexpected' I need to know?)
    Thank you -Clockfrog

    The type of action you describe - 'download to computer and delete off server' - is something you can do with a Pop mail account.
    Pop mail accounts can only see the server Inbox. They connect with server, look in server Inbox for any emails not previously downloaded, then downloads those emails to Thunderbird mail account Inbox.
    You cannot change an IMAP into a POP mail account.
    You would need to create a new Pop mail account.
    * 'File' > 'New' > 'Exisiting mail account'.
    * enter your name, email address and password you use to access that mail account via webmail.
    * click on 'Continue'
    * Thunderbird will try to look up configuration
    * check details, if it says IMAP then change to Pop and if necessary click on 'Manual Config' button to make any changes to server settings.
    * click on 'Done' when finished.
    You can choose to download and immediately delete off the server or leave on the server for xx days or leave on the server until you delete an email.
    Check your settings before you choose to download. I would suggest that until you are certain that you have managed to download everything, select to 'leave emails on server'. You can modify this here:
    * Tools > Account Settings > Server Settings
    or
    * 3bar menu icon > Options > Account settings > Server Settings
    If you have emails in other folders on the server which you need to download:
    * logon to webmail via a browser
    * select a folder and move emails into server Inbox
    * in Thunderbird click on 'GetMail' to download those emails.
    * move emails into suitable folders
    * Repeat for each folder on the server.
    Once you have done this, all future incoming emails to server Inbox will be downloaded to Thunderbird.

  • When I listen to music on my iPhone and pause it, if I come back to it later, the playlist has started over. I have a 4S running on iOS 7.0.4. Is there any way to keep this from happening so that my playlist will start off where I last was?

    When I listen to music on my iPhone and pause it, if I come back to it later, the playlist has started over. I have a 4S running on iOS 7.0.4. Is there any way to keep this from happening so that my playlist will start off where I last was?

    Dear Jody..jone5
    Good for you that can't update your iphone because I did it and my iphone dosen't work for example I can't download any app like Wecaht or Twitter..
    Goodluck
    Atousa

  • Status keeps changing from invisible to online: why the issue is ignored?

    There is a serious issue raised in the parallel thread, which is critical for many people: "Status keeps changing from invisible to online" (initiated on ‎16-11-2014 by b.agne, Mac section). In short, when starting using a device, the Skype status changing from "invisible" to "online" - sometimes just for a moment, though enough for others to notice you. These affects very much any type of devices. I am sure the issue has already led to multiple personal crisises and potentially financial losses due to buseness partnership issues (I came close to that myself, and now use anything but Skype for business). The question is: WHY the issue is completely ignored by Skype, Microsoft and expert comunity? Please post the solution if anybody knows how to fix the issue, or suggest how to make Microsoft to know that it should be fixed. Kind regard...

    Hi, I also have the same issue. I change the status to Invisible and a later on it is already as "Online", without having even touched/opened Skype. The only way that I see this may happen is that I have the app installed on the smartphone, but before it never had this issue, but from some month ago it started. Any correction or suggestion to work around this issue? Regards

  • When I am using the browser for a while and try to use ANY search bar and hit the "search" button it does a whopping NOTHING is there anyway of keeping this from happening?

    Whenever I am using Firefox mobile - either regular, beta or aurora and go to search for something like through the Google search page and attempt to search for something the search bar does nothing and hitting the enter button instead doesn't do anything either. Is there a way to keep this from happening?

    Hi and thanks to not leaving the firefox user alone.
    Cor-el your answer is right as the madperson is and I already knew all these
    answer and I said that before I don’t use any antivirus and I always turn off my firewall from the moment I installed my Windows.
    I even turn off any automatic update for any of my software and I never let any unknown plugins or any thing like that be install without informing me. And if you know some things like Offline Storage and cookies must be to much more than usual and you have to clear them and delete them and I know so much more
    And if you want to know it fixed now. But I don’t know how?
    For understanding my problem read and research about Ixplorer.exe virus it is the same problem about the speed but the different is it doesn’t show any process in task manager like Ixplorer.exe virus
    Bt I have done some things but still I don’t know that’s why it is fixed or not
    First: I searched my system and removed any files have been crated on my system from two days ago since the problem happened.
    And then I used to go about the article in this page and did like this:
    http://answers.yahoo.com/question/index?qid=20080910101846AAazxN5
    but still I don’t know any thing about the problem.
    I can do so many things to fix but I am just curios if that is a virus why it just cut the speed when I am using the browser.
    Please if any one found the reason send me your information I like to know it will improve my knowledge however my problem is solved fro now.

  • My ipod 5th gen ios 7.0.6 crashed and keeps going from the apple logo, going to a black screen, back to the apple logo, then back to the black screen and so on. Furthermore, my laptop doesn't recognise that the iPod is connected. What do I do?

    My ipod 5th gen ios 7.0.6 crashed and keeps going from the apple logo, going to a black screen, back to the apple logo, then back to the black screen and so on. Furthermore, my laptop doesn't recognise that the iPod is connected. What do I do?
    Please help me out as this is very irritating. This has been happening for the last 20-30 minutes. It had roughly half battery left.

    Try:                                               
    - iOS: Not responding or does not turn on
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try another cable       
    - Try on another computer                            
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
      Apple Retail Store - Genius Bar                              

  • I have multiple devices backed up to the same computer each with different data. how do i keep them from syncing all data when i back up or transfer stuff from the computer to a device?

    i have multiple devices backed up to the same computer each with different data. how do i keep them from syncing all data when i back up or transfer stuff from the computer to a device? one is an iphone 6 and the others are ipad mini first gens, each ipad has 64gb and the iphone has 128, need to keep the data seperate as they are not all mine

    Itunes content and pics are NOT part of the backup that itunes performs.
    Backing up, updating, and restoring iPad, iPod touch, and iPhone software
    You should transfer any purchases from iphone regularly:  File>Transfer Purchases  , if they fail to be transferred when you sync.
    You buy one and only one download.  It is your responsibility to move/copy/backup your purchases.
    You can try contacting itunes support and asking for an exception, but they are under no obligation to allow.
    http://www.apple.com/support/itunes

  • Using a Macbook Pro with OSX 10.9.2. When I am typing an email, I get 10  copies of it in the trash folder. How can I keep it from filling up my trash folder?

    Using a Macbook Pro and OSX 10.9.2. When I am typing an email, it fills my trash folder with multiple copies of the email before I send it. I can have over 10 copies every time. How can I keep this from happening and filling my trash folder?  I did not have these issues with previous version of OSX.

    writing Email produced in multiples in all mail
    Multi Copies of Drafts To Gmail Server

  • How do I keep applications from automatically opening when I power up my Macbook Air?

    How do I keep applications from automatically opening when I power up my Macbook Air?

    When you Shutdown or restart, uncheck this option.
    Regards,
    Captfred

  • How can I keep lion from generating .DS_Store files on windows network partitions, but not disable it for all network partitions?

    How can I keep lion from generating .DS_Store files on windows network partitions, but not disable it for all network partitions?  I am fimilar with changing the setting for all network partitions(defaults write com.apple.desktopservices DSDontWriteNetworkStores true), but that is undesirable when I connect my laptop to my home network. A preferable solution would be where I could control the writing of these files based on disk format (NTFS vs HFS+).

    Go to MacUpdate or CNET Downloads and search for ds_store. There are numerous utilities for preventing them from being transferred to Windows systems.

  • How do I keep itunes from putting things into the cloud after I've downloaded them?

    Hello - Not everyone lives in Silicon Valley or New York City.  I have a relatively slow internet connection so it takes about 2 hours to download a 45-minute tv episode.  Yesterday I did that, and today I went to watch it and it had been put back in the cloud!  "No problem," says Apple, "You can download it again."  It takes f**** 2 hours to download it again.  How can I keep Itunes from putting things I've already downloaded back into the cloud?

    How do I keep itunes from putting things into the cloud after I've downloaded them?
    You don't. They are in the cloud as soon as you make a purchase. As in immediately/right now. They don't get uploaded from yoru computer to the cloud.
    Did you delete it after you watched it?

  • Calling a method on a jFrame from a jPanel that created by the jFrame

    Hi all
    I can not for the life of me work out how to do this.
    Calling a method on a jFrame from a jPanel that created by the jFrame.
    I have used this code to set a handle for one jPanel to another.
    i.e I can create new jpanel and pass in handles from one to another but not back to the jFrame.
    // this is sudo code
      private Panel_Top topPanel;
      private Menu_Panel menuPanel;
      private DataPanel dataPanel;
    //create new
        topPanel = new Panel_Top();
        menuPanel = new Menu_Panel();
        dataPanel = new DataPanel();
    // add handles from one to another
        menuPanel.setDataPanel(dataPanel);
        topPanel.setDataPanel(dataPanel);
        topPanel.setMenu_Panel(menuPanel);
        dataPanel.setMenu_Panel(menuPanel);
    // in each class I use this to set
      public void setDataPanel(DataPanel dataPanel) {
        this.dataPanel = dataPanel;
      }But I can not seam to get a handle back to the jFrame that created it.
    Please help
    as you can see I am trying but no luck so far
    Thanks

    class Life extends JPanel{
          pulic Life( JFrame owner )
                owner.doSomething(); // pass the JFrame to the constructor and feel free to use it
    }[code[                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Blue screen of death, and continous reboot.  Phone never actually boots up, just keeps going from reboot to blue screen and back again.  Any suggestion?

    Blue screen of death, and continous reboot.  Phone never actually boots up, just keeps going from reboot to blue screen and back again.  Any suggestion?

    Hello jared1915
    If you are stuck in that loop, the next step would be to restore your iPhone. Check out the article below to get your iPhone into recovery-mode and restore it in iTunes.
    If you can't update or restore your iOS device
    http://support.apple.com/kb/HT1808
    Regards,
    -Norm G.

Maybe you are looking for