Repaint() being delayed by Thread.sleep()

Hello, I am programming a Memory-like card game, where the user picks cards and if they match they stay flipped over, but if they don't match the cards will be displayed for a second and then flipped back over. However, I am running into a problem when the cards do not match, the game will wait (using Thread.sleep()) and then flip the cards back over. The problem is that the second card picked, that is determined to not be a match, is not showing the face before the cards are returned to the hidden state. I think that it is being flipped twice in a row at the end of the sleep(), therefore never actually displaying the front of the card. I have tried putting repaint() everywhere, and there is one before the sleep(), but it still doesn't seem to work properly. Here is the code for my mouse clicked event. Thanks for any help!
  public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    Card temp = null;
    for (int i = 0; i < 52; i++) {
      temp = cards.getCard(i);
      if (temp.contains(x, y)) {
        if (temp.isFront() == true)
          return;
        temp.swapImg();
        this.repaint();
        if (flipped == null) {
          flipped = temp;
        } else {
          if (temp.getVal() == flipped.getVal()) {
            // we have a pair
          } else {
            // cards don't match.. start over
            try {
              Thread.sleep(500);
            } catch (InterruptedException ie) {
              System.out.println("Thread was interrupted!\r\n");
            temp.swapImg();
            flipped.swapImg();
          flipped = null;
        break;
  }

Don't use Thread.sleep() inside a Listener. You are blocking the EDT which prevents the GUI from repainting itself.
Use a Swing Timer to schedule the flipping of the cards.

Similar Messages

  • Work manager using thread.sleep or delay doesn't work

    Hi all,
    I used Spring framework and oracle weblogic 10.3 as a container.
    I used workmanager for manage my thread, I already made one thread that managed by workmanager. Fortunately spring provide the delegation class for using workmanager, so I just need to put it on applicationContext.xml.
    But when I put the "while" and TimeUnit for sleep the process on desired delayed time, the deployment process never finished. It seems the deployment process never jump out from while loop for finishing the deployment.
    Why?, As I know using typical thread, there is no issue like this. Should I use another strategy for make it always loop and delay.
    This is my simple code :
    import java.util.concurrent.TimeUnit;
    import org.springframework.core.task.TaskExecutor;
    public class TaskExecutorSample{
         Boolean shutdown = Boolean.FALSE;
         int delay = 8000;
         TimeUnit unit = TimeUnit.SECONDS;
         private class MessageGenerator implements Runnable {
              private String message;
              public MessageGenerator(String message){
                   this.message = message;
              @Override
              public void run() {
                   System.out.println(message);
         private TaskExecutor taskExecutor;
         public TaskExecutorSample(TaskExecutor taskExecutor){
              this.taskExecutor = taskExecutor;
              try {
                   while (shutdown.equals(Boolean.FALSE)){
                        this.printMessage();
                        unit.sleep(delay);
              } catch (Exception e) {
                   System.out.println(e.getMessage());
         public void printMessage() {
              taskExecutor.execute(new MessageGenerator("Print this Messages"));
    Really thanks in advance.
    Regards,
    Kahlil
    Edited by: Kahlil on May 26, 2010 2:38 PM
    Edited by: Kahlil on May 26, 2010 2:42 PM

    Hi,
    i m not sure whether it's an issue with Spring or not. But i tried using Thread.sleep(1000) in a Simple webapplication to see Workmanagers works properly or not. I found that it works extremely great: http://weblogic-wonders.com/weblogic/2010/01/24/workmanager-at-webapplication-level/
    Thanks
    Jay SenSharma

  • What's wrong to put Thread.sleep in a session bean?

    i am working on a trading platform and i think there is a design flaw. The part i am working on is the Order Management module. When an order value object is published to a JMS topic and picked up by a MDB. The MDB, in turn, calls a session bean (could be stateless, I didn't check), OrderEngineBean. After this bean saves the order vo into database and broadcast the message to all involved parties, it suspends for 12 sec, using Thread.sleep, so other parities might have a chance to update the vo. If no update occurs, the order is considered expired and abandoned.
    It looks awkward to me to use a Thread.sleep in a session, but I haven't come out with a better idea to deal with the scenario like above.
    Anyone can help me out?
    Thanks a lot!
    Sway

    Setting the property "max-beans-in-free-pool" is not the answer to this issue. By setting this property to 1, the container merely instantiates and keeps one instance of the bean in the free pool at the "start" of the app server. But if the container comes across more than one requests for the same EJB simultaneoulsy, then it will create new instances at that time to handle the requests simultaneously.
    You are seeing intermixed log messages between two threads because these messages are being logged from two different instances of the EJB and NOT the same instance of the EJB. The container does synchronizes the calls on "a method" on "a instance". So what you are seeing are the messages coming from "a method" on "two different instances" of the same EJB.
    You can refer to the EJB 2.0 specification section 6.11.6 Non-reentrant instances for details about simultaneous access to the same session object.

  • Problem with Thread.sleep()

    hi all,
    I am trying Thread.sleep() method to introduce a delay. In the program i ask the user to specify the value to be entered in Thread.sleep() (to indicate the amount of delay desired by the user). but strangely, if a low value is entered, i get a different result which actually should not happen as the rest of the calculation remains the same, only the amt of delay changes.
    could anyone help me with this
    cheers
    ankit

    [url http://forum.java.sun.com/thread.jsp?forum=31&thread=536288]Double-post

  • Java Thread.sleep() on Windows 8 stops in S3 sleep status

    There's a desktop application that uses Thread.sleep() to achieve long (minutes or hours) delays. This same application has been working fine from Windows XP through Windows 7. The application calculates how far in the future it needs to do something, then hits a Thread.sleep(msToWait). This has been working fine, even if the system happens to go into S3 or S4 sleep state during the wait.  All is good as long as the machine is awake at the time when the sleep expires.
    As of Windows  8 (and 10), though, the code after Thread.sleep() does not execute "on time" if the machine has been in S3 during the sleep interval. It appears that the machine begins executing code at "msToWait" plus the time the machine has been in S3.
    Earlier versions of Windows did not exhibit this behavior; code after Thread.sleep() waited the right amount of time, irrespective of sleep status.
    A test program and procedure were developed. The procedure is to 1) run the program, 2) cause the machine to sleep for about a minute, then 3) wake the machine and wait for the program to finish.
    If this the program is run on Windows 10 (reporting as 8) with JVM Version: 25.40-b25, it fails (the 63589 corresponds to the minute that the machine was in S3):
    C:\Users\Tester\Downloads>SleepTester.exe
    Wed Apr 01 10:47:35 PDT 2015 Using default number of minutes: 5
    Wed Apr 01 10:47:35 PDT 2015 You can use "SleepTester -minutes 10" to have it sleep for 10 minutes, for example.
    Wed Apr 01 10:47:35 PDT 2015 JVM Version: 25.40-b25 Windows Version: Windows 8
    Wed Apr 01 10:47:35 PDT 2015 The program will now wait for 5 minutes.  Expect wrap-up at Wed Apr 01 10:52:35 PDT 2015
    Wed Apr 01 10:53:38 PDT 2015 The system has come through the Thread.sleep(300000).
    Wed Apr 01 10:53:38 PDT 2015 This should be a low number: 63589
    Wed Apr 01 10:53:38 PDT 2015 This appears to be operating incorrectly...the expected sleep time has NOT been achieved.
    Wed Apr 01 10:53:38 PDT 2015 Program is ending.
    If the process is run on Windows 7, it does not fail:
    Wed Apr 01 17:12:18 EDT 2015 Java Runtime Version: 1.8.0_31-b13 JVM Version: 25.31-b07 Windows Version: Windows 7
    Wed Apr 01 17:12:18 EDT 2015 The program will now wait for 6 minutes.  Expect wrap-up at Wed Apr 01 17:18:18 EDT 2015
    Wed Apr 01 17:18:18 EDT 2015 The system has come through the Thread.sleep(360000).
    Wed Apr 01 17:18:18 EDT 2015 This should be a low number: 0
    Wed Apr 01 17:18:18 EDT 2015 Program is ending.
    This is the guts of  test program:
    [code]
    public static void main(String[] args) throws Exception {
       System.out.println(new Date() + " Java Runtime Version: " + System.getProperty("java.runtime.version") + " JVM Version: " + System.getProperty("java.vm.version") + " Windows Version: " + System.getProperty("os.name"));
       long msDelay = mMinutes * 60 * 1000;
       long wakePoint = new Date().getTime() + msDelay;
       System.out.println(new Date() + " The program will now wait for " + mMinutes + " minutes. Expect wrap-up at " + new Date(wakePoint));
       Thread.sleep(msDelay); // If the machine goes into S3 during this interval, it should not matter, as long as it's awake when it fires.
       System.out.println(new Date() + " The system has come through the Thread.sleep(" + msDelay + "). ");
       long msAccuracy = Math.abs(new Date().getTime() - wakePoint);
       System.out.println(new Date() + " This should be a low number: " + msAccuracy);
       if (msAccuracy > 1000) System.out.println(new Date() + " This appears to be operating incorrectly...the expected sleep time has NOT been achieved.");
       System.out.println(new Date() + " Program is ending.");
    [/code]
    Was the change in behavior from earlier versions of Windows intentional?  Is it something that the JVM is controlling, or is there a difference in the underlying OS that is beyond the control of the JVM?

    I might need to create a work-around whereby I maintain a watch of the msDelay and the system clock.  If there is a discontinuity (which would only happen on Windows 8 or higher), then I would repair the msDelay value.
    A separate (but related) question:
    Can I conclude that since older JVM's running on Windows 8 still have the problem, that it's a Windows issue, and not a JVM issue?

  • Confusion using Thread.sleep() method

    I tried it in this program
    class NewThread implements Runnable {
      String name; // name of thread
      Thread t;
      NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
      // This is the entry point for thread.
      public void run() {
        try {
          for(int i = 5; i > 0; i--) {
            System.out.println(name + ": " + i);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
          System.out.println(name + "Interrupted");
        System.out.println(name + " exiting.");
    class MultiThreadDemo {
      public static void main(String args[]) {
        new NewThread("One"); // start threads
        new NewThread("Two");
        new NewThread("Three");
        try {
          // wait for other threads to end
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          System.out.println("Main thread Interrupted");
        System.out.println("Main thread exiting.");
    }the output is
    one: 5
    two: 5
    three 5
    delay of 1 second
    one:4
    two: 4
    three: 4
    delay of 1second
    what all i know about sleep() is that it pause the currently executing thread for specified time. hence in above program when first thread runs and prints value 5 then it should get paused for 1 second cause there is Thread.sleep(1000) after println() statement.
    and output should be
    one: 5
    delay of 1 second
    two: 5
    delay of 1 second
    three: 5
    delay of 1 second
    but this is not actually happens. may be i am wrong about Thread.sleep method() or something else.
    would you guys please clear it?
    regards
    san

    Thread.sleep() only sleeps the current thread. As each thread runs concurrently they all print concurrently and all sleep concurrently.

  • Alternative to Thread.Sleep in catch?

    Is there any other way to make the code wait than using Thread.Sleep in catch, because Thread.Sleep disturbs other objects on my form. Here is what I'm trying to do:
    Try{
    //do something
    catch
    // wait 10 seconds
    //retry

    Timers are a bit of a nuisance what with keeping your form in memory even when you try and dispose the things.
    You could push the thing you're doing onto another thread.
    Use async await.
    You could then use Task.Delay.
    A very simplified example:
    private async void Button_Click1(object sender, RoutedEventArgs e)
    await Task.Delay(2000);
    // Do something
    Because that's an async method processing returns to the caller when it hits the await.
    That then pauses 2 seconds without impinging on your UI thread.
    Before the separate thread continues with the code after your await.
    You could put your try catch into a method like that and it'd do what you want without a timer.
    10 seconds seems a bit of a short time by the way.
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • Alternative to Thread.sleep() function

    Dear Experts,
    I am developing an application that requires sleep times on the order of nanoseconds. I tried using the Thread.sleep(long milliseconds, int nanoseconds) function, but I found that the smallest time the function will sleep for is 1 millisecond (i.e sleep(1,0) sleeps for the same amount of time as sleep(0,1)). I am pretty sure that the smallest increment you can set a timer to is one millisecond as well. Are there functions out there that can output nanosecond delays?
    Thanks

    I am developing an application that requires sleep
    ep times on the order of nanosecondsThread.sleep() gives you whatever the OS exposes. If the OS doesn't support sub-millisecond sleep times, then you won't get it.
    More importantly, Thread.sleep() does not guarantee sleep times. If the OS scheduler decides that there are a dozen other processes with higher priority (or a dozen other threads in your process), you may find that you've slept for many milliseconds, maybe even seconds.
    If you want more info, I recall www.javaworld.com having an article on sub-millisecond timing. You might want to check there to see if they say anything about sleep times.

  • Updating frame content between Thread.sleep() calls

    I have several JLabels in a Frame. What I want is to update the content of the labels (to be more precise, the ImageIcons), but with pauses in between each update (lets say 1 second). So, I want to change the content of one label, have those changes show on screen, then, wait for a second and change the content of the second label, show the changes, wait for a second, change the next label, and so on...
    What I'm doing is:
    change label 1
    Thread.sleep(1000);
    change label 2
    Thread.sleep(1000);
    change label 3
    Thread.sleep(1000);
    ...And the problem is that the individual changes are not shown on screen until the whole process has finished. It does pause after each change, but the change to the particular label is not shown afterwards. Then, when the whole process is finished, the changes to all the labels are shown simultaneously on screen.
    I have tried calling repaint() and validate() after each call to Thread.sleep(), but it makes no difference.
    Why are the changes not updated on screen until the end?
    How can I achieve what I'm trying to do?
    Many thanks in advance.

    You're sleeping in the main thread, so you're holding up the paint thread too...
    I'd trying extending each label / visual component, to include it's own timer and thread.
    eg. ( not compiled nor tested, but addresses all the main points... )
    regards,
    Owen
    public class myLabel extends JLabel implements runnable
        boolean animate = true;
        Thread paintThread;
         public myLabel ( )
              super();
              paintThread = new Thread ( this );
         public void startAnimation ( )
              if ( animate == false )
                 animate = true;
                 paintThread.start();
         pubic void stopAnimation ( )
             animate = false;
         public void run ( )
               while ( !animate )
                   Thread.sleep ( 1000 );
                    final Runnable runnable = new Runnable()
                        public void run()
                              // change label text
                              // Make any Swing / GUI changes here                      
                        } // run
                   };    // runnable
                   // force/flag this label as requiring a repaint
                   invalidate();              
                   // NB : You must use this to avoid multi-threaded problems with Swing
                   SwingUtilities.invokeLater(runnable);
    }

  • Realtime equivalent to Java's Thread.sleep()?

    I have an application that I want to guarantee that when I call Java's Thread.sleep(n) the thread will sleep for precisely that amount of time, or close to it at least. What we recently encountered though was that if the "wall clock" time is changed in one thread while a sleep is occurring in another thread, this clock change will impact when the sleeping thread will wake up.
    In our case, we had a simple Thread.sleep(1000), and during that one second period another thread set the clock back two minutes. The sleeping thread ended up sleeping roughly two minutes and a second instead of just a second. Apparently this is a "feature" of Thread.sleep(), and I can see in some cases (e.g. a task scheduler based on wall clock times) where this is exactly the behavior you'd want. However, in our case, we want the sleep function to sleep by the amount we specify, regardless of changes to the wall clock time. Is there a way to do this in Java? We are using JDK 1.5.

    You can use methods which rely on the nanoTime() (based on the number of clock cycles since the processor last reset)
    Classes such as LockSupport.parkUntil(someObject, nanoTime) may give you the accuracy/consistency you want. In this case you always wait the full delay.(and not unpack it)

  • What is an alternate to Thread.Sleep()?

    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?

    watwatacrazy wrote:
    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?I am in no way condoning this idea, because as mentioned it is a very bad idea.
    However. Not lettiing you throw exceptions is not a reason to not do something. All it means is that you need a catch block. You should review the exceptions part of the Java tutorial found here [_Java Tutorial : Exceptions_|http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]

  • Menu and Thread.sleep(5000) or Thread.currentThread.sleep(5000)

    Hi,
    I am using JMenu and switchable JPanels.
    When I click on a MenuItem the follownig code should starts
        cards.add(listenPanel,  "listenPanel");
        cardLayout.show(cards, "listenPanel");
        try{
          Thread.sleep(5000); //in ms
          PlayMP3Thread sound = new PlayMP3Thread("sound/ping.mp3");
        } catch(Exception e) {
          e.printStackTrace();
        }It seems to be what I want to reach, but it does not work the way I want it to.
    I would like the Panel to show right away, then wait 5s and then play the sound.
    BUT what it does is freez the unfolded menu for 5s, then plays the sound and after that it shows the new Plane.
    Can you tell me why this is??

    This might be what you want
    package tjacobs.thread;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Semaphore;
    import tjacobs.ui.Eyes;
    import tjacobs.ui.util.WindowUtilities;
    public class ThreadForMultipleAnytimeRuns extends Thread {
         private Runnable mRunnable;
         private Semaphore mSemaphore;
         public ThreadForMultipleAnytimeRuns(Runnable arg0) {
              super();
              init(arg0);
         private void init(Runnable r) {
              mRunnable = r;
              mSemaphore = new Semaphore(0);
              setDaemon(true);
         public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
              super(arg1);
              init(arg0);
         public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
              super(arg0, arg2);
              init(arg1);
         public void run () {
              try {
                   while (!isInterrupted()) {
                        mSemaphore.acquire();
                        mRunnable.run();
              catch (InterruptedException ex) {}
         public void runAgain() {
              mSemaphore.release();
         public void runAgain(int numTimes) {
              mSemaphore.release(numTimes);
         public void stopThread() {
              interrupt();
         public int getSemaphoreCount() {
              return mSemaphore.availablePermits();
         public Runnable getRunnable() {
              return mRunnable;
         //The setRunnable method is simply not safe, and
         //trying to make it safe is going to effect performance
         //Plus I can't really see a gain in being able to set
         //The runnable on one of these threads. Just create
         //a new one!
         public synchronized void setRunnable(Runnable r) {
              if (getSemaphoreCount() > 0) {
                   try {
                        wait();
                   catch (InterruptedException ex) {
                        return;
              mRunnable = r;
         public static void main(String[] args) {
              final Eyes eyes = new Eyes(true);
              //eyes.addMouseMotionListener(eyes);
              Runnable r = new Runnable() {
                   public void run() {
                        eyes.blink();
                        try {
                             Thread.sleep(100);
                        catch(InterruptedException ex) {}
              final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
              ar.start();
              eyes.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        ar.runAgain();
              eyes.setPreferredSize(new Dimension(60,20));
              WindowUtilities.visualize(eyes);
    //          JFrame jf = new JFrame();
    //          jf.add(eyes);
    //          jf.pack();
    //          jf.setLocation(100,100);
    //          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          jf.setVisible(true);
    }

  • Contiunous running programs: Thread.sleep vs. Scheduled Tasks

    Hello,
    I have simulation programs that should run continuously for weeks at a time. I am seeking any advice or comments on the best way to do something like this.
    Some programs run every 30 seconds; others run once per hour; others run once per day. These programs involve simulating the use of a popular website by reading web pages and inserting records into Oracle 9i databases.
    As far as the "every 30 seconds" program, I use Thread.sleep to pause the program for each interval. Is this a good method?
    What about programs running once per hour or per day? I have used the Windows XP Scheduled Task program to execute the program. Is this a good method?
    Does anybody know of a better way to do such things?
    Any comments or helpful links are greatly appreciated.
    Thank you,
    Logan

    I have simulation programs that should run
    continuously for weeks at a time. I am seeking any
    advice or comments on the best way to do something
    like this.If you have a simulator, does it have to simulate time on a one to one basis. Could it not simulate 30 seconds, every 3 seconds and thus not need to run for the full week. If you have to run in real time, what are you simulating.
    Some programs run every 30 seconds; others run once
    per hour; others run once per day. These programs
    involve simulating the use of a popular website by
    reading web pages and inserting records into Oracle
    9i databases.
    As far as the "every 30 seconds" program, I use
    Thread.sleep to pause the program for each interval.
    Is this a good method?No. Sleep for 30 seconds just means there is atleast 30 seconds delay from the end of the last task to the start of the next task. This could means every 30.1 seconds or even every 33 seconds depending on how long the task takes to run.
    If you create a single ScheduledExecutorService you can run a task with any period you suggest with a dynamic number of threads.
    e.g.
    Execuotrs.newScheduledThreadPool(1);
    >
    What about programs running once per hour or per day?See previous.
    I have used the Windows XP Scheduled Task program to
    execute the program. Is this a good method?If it is a couple of times per day or per week this is a good choice.
    >
    Does anybody know of a better way to do such things?see previous.

  • Long Delay Going to Sleep Mode

    This is a strange problem that just recently started.
    My Mac delays going to sleep from both my login and hers whenever my she is logged in. If she isn't logged in, everything works fine and the computer immediately goes to sleep as it should.
    I have zapped my parameter memory, repaired permissions and verified that the hard drive is working properly. I've shut down all apps running under her login. There are 90 some processes running in the background, but nothing looks suspect.
    Maybe I should try dumping her login preferences?
    Any ideas? TIA.
    Rob

    Okay, some further troubleshooting has revealed that this problem is being caused by ARD. Last week I turned on Remote Management under Sharing. I checked my log files today and discovered several recent crash logs for my ARDAgent.
    *Exception Type: EXCBADACCESS (SIGBUS)*
    *Exception Codes: KERNPROTECTIONFAILURE at 0x0000000000000000*
    Turning off Remote Management fixed the problem. I noticed that Apple has a new update out for Remote Management (ARD):
    *Apple Remote Desktop 3.2.2 Client Update*
    *The 3.2.2 update is recommended for all Apple Remote Desktop clients and addresses several issues related to overall reliability and security.*
    *For detailed information on this update, please visit this website: http://support.apple.com/kb/HT2691*
    I'll try the update to see if it fixes the problem.

  • Using Thread.sleep()

    When I put Thread.sleep() in my code, the debugger says I need to catch it. How do I do that?

    But in general, you don't want to just smother exceptions like that. It's okay when you're sleeping (or can be) because often if you're interrupted, you want to just ignore it and move on. However, there's more to handling exceptions than just an empty catch block.
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

Maybe you are looking for

  • Question about Sennheiser headphones for my Zen Ph

    I just bought these Sennheiser headphones (CX 300-S) for my Zen Photo and when the lights are on I get a buzzing noise but when the lights go off the buzz is gone. Does anyone have any clue why this is? The headphones cost me a pretty penny and they

  • How can we speed up delta Process?

    Hi All, As per control parameter settings we have max. no processes as 6 and 10 data packages for one Info doc and its the same for that particular infosource settings. but when we schedule the delta info package( R/3 - BW ODS) it is using only one p

  • Oracle Express Dimension attributes

    Hi, I would like to create a multi-dimensional database with Oracle Express. I don't how to define dimensions with attributes. Is anybody can help me? Thank you.

  • Query to find match on two fields where third does not..

    Struggling with this one.. Stripped down example data SECTION     GROUPID     SUBGROUPID     COMPONENT     PNUM     USERNAME HVAC     AC     MOTOR          HOSE          111.1     BOB HVAC     AC     MOTOR          HOSE          111.2     BOB HVAC   

  • KeyEvent with JTree

    I want to implement the hot key Ctr_c/Ctr_v for the copy/paste function in the JTree. I added a KeyListener to this JTree and implemented the keyPressed() method as following: public void keyPressed(KeyEvent e){ if( e.isControlDown()){ if ( (e.getKey