Simulate multiple simultaneous key presses with applescript?

Is it possible to simulate holding down multiple keys with applescript? No modifiers, just letters.
For example;
holding down d,o,n,k,e and y keys simultaneously for 1 second then letting go?
so far I have this:
on run {input, parameters}
          tell application "System Events"
       keystroke 4
       keystroke 1
       keystroke 37
       keystroke 9
       keystroke 2
       keystroke 17
          end tell
          return input
end run
Can anyone show me how to tell it to hold for 1 second, but more importantly is this actually possible and am I even on the right track?
Cheers,
Marty

You should be able to achieve this via the key down and key up commands, rather than keystrokes.
As the name implies, a keystroke is a simple, single press of a key whereas the key down simulates the pressing of a key and key up simulates the release.
Off hand I have no idea how it will respond to multiple keys, and I'm not inclined to try, but this should point you in the right direction:
tell application "System Events"
          key down "donkey"
  delay 1
          key up "donkey"
end tell

Similar Messages

  • Simultaneous key press on the keyboard GX600

    hello guys,
    i bought a MSI GX-600 thinking that it could accommodate my gaming needs however i found out that it cannot allow more than 2 simultaneous key presses on the keyboard. its supposed to be a gaming laptop right? i cannot play keyboard bashing games with this unless i use a gamepad or an external keyboard. have you experienced this on your laptop? 
    do you think an update of the bios will do the trick?
    try this link to test if your keyboard can handle more than 2 keypress at the same time:
    http://blog.nobien.net/2008/05/12/more-than-two-simultaneous-key-presses-and-keyboardeventkey_down-woes/
    btw, i like this forum. 

    Quote
    do you think an update of the bios will do the trick?
    No, no, no, it won't, so please don't try it!
    Also, if you read the comments in the link you posted, your answer is there:
    Quote
    By Tony Fendall on May 12, 2008 | Reply
    The problem comes from the way in which the signal for the pressed keys moves from your keyboard to your computer. The signal is only 8-bit, and there are limits to how the signal can be changed to represent more than one key being pressed in combination.
    Long story short, the guys who designed the origional keyboards made a descision to support all two key combinations, and then selected as many three key combinations as they could support with the hardware. This meant that some combinations had to be left out, and they had to make a descision about which ones were more important.
    It just happens to be that they chose not to support three key combinations which involve the up arrow key. I do not think there is any solution to this problem…
    If you're playing games, why not just remap the keys in the game's settings?

  • Catching Alt Key Press with the Key Down Filter Event

    I am writing an application that requires specific key combinations using ctrl, shift, and alt in addition to a function key (F1, F2, F3, etc).  The application works great except for when I try to catch an alt key press.  The alt key press does not seem to fire an event eventhough it is an option in the PlatMods cluster as well as the VKey enum.  When I press the alt key when my application is running the cursor changes to a normal mouse pointer from the usual finger pointer and prevents any other key presses from going through (in addition to not firing an event itself).
    I have tried completely removing the run-time menu, which doesn't seem to help.  I currently discard all keys after I handle them in my event structure.
    I really hope that the only solution isn't using a Windows DLL.  Any suggestions or ideas at all would be greatly appreciated.
    Thanks,
    Ames

     Hi Ames
    As Kileen has said Khalid has already given you a good solution to detect the ALT key.
    I have another approach that might let you stick to your event-driven approach. I suggest that you have another loop in your app that polls the keyboard using the Input Device utility vi's. When this poll loop sees an ALT + KEY combo it raises a dynamic user event and will be processed in your event structure. This means you can keep your key down filter event to process the CTRL + KEY and SHIFT + KEY events.
    Example attached in 7.1
    cheers
    David
    Attachments:
    Catching Alt Key Press Poll with Events(151551).vi ‏89 KB

  • Cannot establish multiple simultaneous PPTP connections with the CISCO 1841.

    Hello everyone;
    I have recently tested a PPTP connection with a CISCO 1841 router and got success. I have configured a windows 7 client and successfully connected to the router and was able to access the documents in the server PC that I have mentioned in the attached diagram. I have created number of different users  in the CISCO 1841 too. While some one is having a connection, another user cannot connect to it, which means multiple simultaneous connections aren't possible. Do I have to create a ACL for the PPTP and if yes, How ? 
     FastEthernet0/0 is up, line protocol is up
      Internet address is 192.168.100.1/25
      Broadcast address is 255.255.255.255
      Address determined by non-volatile memory
      MTU is 1500 bytes
      Helper address is not set
      Directed broadcast forwarding is disabled
      Outgoing access list is not set
      Inbound  access list is 100
    Proxy ARP is enabled
    Local Proxy ARP is disabled
    Security level is default
    Split horizon is enabled
    ICMP redirects are always sent
    ICMP unreachables are always sent
    ICMP mask replies are never sent
    IP fast switching is enabled
    IP fast switching on the same interface is disabled
    IP Flow switching is disabled
    IP CEF switching is enabled
    IP CEF Feature Fast switching turbo vector
    IP multicast fast switching is enabled
    IP multicast distributed fast switching is disabled
    IP route-cache flags are Fast, CEF
    Router Discovery is disabled
    IP output packet accounting is disabled
    IP access violation accounting is disabled
    TCP/IP header compression is disabled
    RTP/IP header compression is disabled
    Policy routing is disabled
    Network address translation is enabled, interface in domain inside
    BGP Policy Mapping is disabled
    WCCP Redirect outbound is disabled
    WCCP Redirect inbound is disabled
    WCCP Redirect exclude is disabled
    Inbound inspection rule is SDM_LOW
    --------------------------------------------------------------------------------------------ACL 100-----------------------------
    deny icmp any any echo-reply
    deny ip host 255.255.255.255 any
    deny ip 127.0.0.0 0.255.255.255 any
    deny ip host 66.163.169.186 any
    permit ip any any (122467027 matches)

    As long as you have the inspection engine enabled on the ASA, it shouldn't freak out of the different IP as it will inspect the call signalling and will NAT it accordingly, BUT, for simplicity, I agree with you, it would cause a lot of troubleshooting headache if there is problem as well as reconfiguration of IP on the host ends.
    Here is the NAT FYI:
    object network obj-10.10.96.0
       subnet 10.10.96.0 255.255.255.0
    object network obj-192.168.96.0
       subnet 192.168.96.0 255.255.255.0
    object network obj-10.10.14.0
       subnet 10.10.14.0 255.255.255.0
    object network obj-10.1.0.0
       subnet 10.1.0.0 255.255.255.0
    object network obj-192.168.1.0
       subnet 192.168.1.0 255.255.255.0
    object network obj-10.10.11.0
       subnet 10.10.11.0 255.255.255.0
    object network obj-192.168.11.0
       subnet 192.168.11.0 255.255.255.0
    nat (inside,outside) source static obj-10.10.96.0 obj-192.168.96.0 destination static obj-10.10.14.0 obj-10.10.14.0
    nat (inside,outside) source static obj-10.1.0.0 obj-192.168.1.0 destination static obj-10.10.14.0 obj-10.10.14.0
    nat (inside,outside) source static obj-10.10.11.0 obj-192.168.11.0 destination static obj-10.10.14.0 obj-10.10.14.0

  • Simultaneous ASDW key press undetected

    Hi guys, I'm currently developing a game that uses ASDW buttons for its movement system
    During one of my testing session, i realized that if i press 2 buttons simultaneously, (ex: A and S), both events would be dispatched one after the other (just like what i assume they would do)
    But if i press 3 buttons simultaneously, (ex: A, S and D), the last keypress (D) will go undetected
    Only after i release one of the keys (either A or S) will the last keypress be detected
    From what i read here ==> http://blog.nobien.net/2008/05/12/more-than-two-simultaneous-key-presses-and-keyboardevent key_down-woes/
    It is said that the problem might had been caused by a hardware issue
    From what i read at wikipedia http://en.wikipedia.org/wiki/Keyboard_%28computing%29
    [quote]
    Some low-quality keyboards suffer problems with rollover (that is, when multiple keys are pressed in  quick succession); some types of keyboard circuitry will register a  maximum number of keys at one time. This is undesirable for games (designed for multiple keypresses, e.g. casting a spell while holding  down keys to run) and undesirable for extremely fast typing (hitting new  keys before the fingers can release previous keys). A common side  effect of this shortcoming is called "phantom key blocking": on some  keyboards, pressing three keys simultaneously sometimes resulted in a  4th keypress being registered.
    Modern keyboards prevent this from happening by blocking the 3rd key  in certain key combinations, but while this prevents phantom input, it  also means that when two keys are depressed simultaneously, many of the  other keys on the keyboard will not respond until one of the two  depressed keys is lifted. With better keyboards designs, this seldom  happens in office programs, but it remains a problem in games even on  expensive keyboards, due to wildly different and/or configurable  key/command layouts in different games.
    [/quote]
    Question
    - What causes this problem is it a hardware issue or a language/flash player problem?
    Because i might be wrong, but i think i've played several non-flash games before that possess the ability to address multiple keypress at the same time
    - Can this problem be fixed?
    Code
    package
            import flash.display.Sprite;
            import flash.events.KeyboardEvent;
            public class Keyboard extends Sprite
                     public function Keyboard()
                            this.stage.addEventListener("keyDown", showKey);
                    public function showKey(event:KeyboardEvent)
                            trace(event.keyCode);
    Any help regarding the matter is greatly appreciated, thank you in advance~

    Quote
    do you think an update of the bios will do the trick?
    No, no, no, it won't, so please don't try it!
    Also, if you read the comments in the link you posted, your answer is there:
    Quote
    By Tony Fendall on May 12, 2008 | Reply
    The problem comes from the way in which the signal for the pressed keys moves from your keyboard to your computer. The signal is only 8-bit, and there are limits to how the signal can be changed to represent more than one key being pressed in combination.
    Long story short, the guys who designed the origional keyboards made a descision to support all two key combinations, and then selected as many three key combinations as they could support with the hardware. This meant that some combinations had to be left out, and they had to make a descision about which ones were more important.
    It just happens to be that they chose not to support three key combinations which involve the up arrow key. I do not think there is any solution to this problem…
    If you're playing games, why not just remap the keys in the game's settings?

  • Detecting multiple key presses

    Using the code below I am trying to detect keypresses for a java applet which involves holding down of several keys at once. I have 2 problems, probably related. Firstly I can only detect 3-4 simultaneous keys being held down and secondly the keyPressed and released! events are continually fired while a key is held down not just when it was first pressed as you would think. I would like to be able to detect up to a maximum of 16 keys being held down at once, is this possible? I am working on a unix system in x-windows which I think accounts for the auto-repeat problem, but why am I having trouble detecting multiple simultaneous keys being held down?
    It there a boolean function I can call to check the state of given keys at a given time, that would be very useful?
    Any help is appreciated.
    Ian
    public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode){
    case java.awt.event.KeyEvent.VK_O: //o
         odown=true;
    break;
    case java.awt.event.KeyEvent.VK_P: //p
         pdown=true;
    break;
    case java.awt.event.KeyEvent.VK_Q: //q
         qdown=true;
    break;
    case java.awt.event.KeyEvent.VK_W: //w
         up=true;
    break;
    case java.awt.event.KeyEvent.VK_A: //a
         left=true;
    break;
    case java.awt.event.KeyEvent.VK_S: //s
         down=true;
    break;
    case java.awt.event.KeyEvent.VK_D: //d
         right=true;
    break;
    }//method keypressed
    public void keyTyped(KeyEvent e) {
    }//method keytyped
    public void keyReleased(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode){
    case java.awt.event.KeyEvent.VK_O: //o
         odown=false;
    break;
    case java.awt.event.KeyEvent.VK_P: //p
         pdown=false;
    break;
    case java.awt.event.KeyEvent.VK_Q: //q
    qdown=false;
    break;
    case java.awt.event.KeyEvent.VK_W: //w
         up=false;
    break;
    case java.awt.event.KeyEvent.VK_A: //a
         left=false;
    break;
    case java.awt.event.KeyEvent.VK_S: //s
         down=false;
    break;
    case java.awt.event.KeyEvent.VK_D: //d
         right=false;
    break;
    }//method keyReleased

    Did you ever find a solution to this problem. I am experiencing a similar problem. I want to be able to disable the auto-repeat function of the keyboard, so that I can tell if the user is holding down the key, or pressing it several times.
    If you have found a solution please let me know at [email protected]
    Thanks,
    Ben Newton

  • Multiple key press's with Bluetooth Keyboard

    I'm ready to update my mac to a new G5 imac and fancy getting the wireless bluetooth keyboard and mouse with it.
    I have one question, has anyone experienced problems when holding down multiple keys on the keyboard and moving the mouse all at once (Using illustrator)?
    In my office I have the misfortune of having to use a PC, I have had a number of wireless keyboard and mouse combos, all of them when using Illustrator and photoshop can not handle multiple key press's and mouse movement.
    ie if I'm duplicating an object by dragging a copy of it across the screen, on the PC it will work but it always "releases" after a couple of seconds and drops the copy in the where I don't want it which gets very frustrating (this only happens with wireless).
    As I do a lot of work at home, I hoping this wont be the case with the mac's bluetooth K & M.
    thanks
    Russell

    The shift key works just fine on my Bluetooth keyboard.  So I would imagine this is an issue with your keyboard.

  • How to select multiple records in ALV with out pressing ctrl

    Hi Experts,
    Is there a way to select multiple records in ALV with out pressing ctrl button on the key board?
    Selection and deselection should allow multiple records.
    any clue is highly appreciated.
    regards,
    Ajay

    The keyboard always plays a role, although with the Shift key you can select blocks of records.
    ○       CTRLclick, CTRLspacebar
    Toggles a selection.
    ○       SHIFTclick, CTRLshift
    Selects the area from the lead selection to the row selected. If no lead selection is set, the selection starts from the first row. In the multiNoLead mode, the selection starts from the row last selected

  • Multiple Key Pressing

    When I hold Tab + w space doesn't work click (I have my controls set as this for a game).
    Is there anyway to make it so i can hold those two keys and have spacebar work?
    Im on a MacBook Pro Retina 13 inch with latest version of yosemite
    Thanks for the help

    Here is an example of both multiple key press and repeat delay ignore. It is a terrible example of animation. Do not us this animation loop in a game. It will flicker far too much.import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame implements Runnable {
      boolean upPressed=false, downPressed=false, leftPressed=false, rightPressed=false;
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addKeyListener(new KeyAdapter() {
          public void keyPressed(KeyEvent ke) {
         switch (ke.getKeyCode()) {
           case KeyEvent.VK_UP: upPressed = true; break;
           case KeyEvent.VK_DOWN: downPressed = true; break;
           case KeyEvent.VK_LEFT: leftPressed = true; break;
           case KeyEvent.VK_RIGHT: rightPressed = true; break;
          public void keyReleased(KeyEvent ke) {
         switch (ke.getKeyCode()) {
           case KeyEvent.VK_UP: upPressed = false; break;
           case KeyEvent.VK_DOWN: downPressed = false; break;
           case KeyEvent.VK_LEFT: leftPressed = false; break;
           case KeyEvent.VK_RIGHT: rightPressed = false; break;
        setSize(250,250);
        setVisible(true);
        Thread timer = new Thread(this);
        timer.start();
      public static void main(String[] args) {
        new Test();
      public void run() {
        while (true) {
          repaint();
          try { Thread.sleep(30);} catch (Exception e) {}
      public void paint(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0,0,getWidth(), getHeight());
        g.setColor(Color.black);
        g.drawString("Up",40,40);
        if (upPressed) g.drawString("Pressed",100,40);
        g.drawString("Down",40,60);
        if (downPressed) g.drawString("Pressed",100,60);
        g.drawString("Left",40,80);
        if (leftPressed) g.drawString("Pressed",100,80);
        g.drawString("Right",40,100);
        if (rightPressed) g.drawString("Pressed",100,100);
    }

  • Multiple key press

    Hai all
    How can a j2me application withstand multiple key press while doing some process.
    Please help me with some ideas
    Thanks
    Jinesh

    Problem is, Redtruck, I can only get FCP to register one press of t. I can reasign select all tracks forward to a single t but when i go to select track forward and press t it asks me if i want to reassign t to this command and then overrides the select all forward shortcut (which reverts back to tttt automatically).
    I can't seem to find a way to enter multiple "t"s when assigning a shortcut.
    I hope this makes sense (I'm almost confusing myself).

  • AppleScript: Keys Pressed test?

    The appleScript below runs fine in OSX 10.4.11, but in OSX 10.5.8, the "Keys Pressed" bit of the "IF" statment is corrupted. How do I get this to work in 10.5.8?
    Thanks
    Note: Apologies that Apple 21st century forum technologies do not preserve formatting, indentation etc...
    on run
    tell application "Finder"
    activate
    make new Finder window
    if (keys pressed) contains "Shift" then
    set bounds of Finder window 1 to {15, 34, 1520, 585}
    else
    set bounds of Finder window 1 to {15, 616, 1520, 1210}
    end if
    set current view of Finder window 1 to column view
    end tell
    end run
    on reopen
    run
    end reopen

    taylor.henderson wrote:
    William Donelson wrote:
    Thank you, all. Very interesting and helpful.
    Why do you think AppleScript cannot detect ShiftDowns? Seems strange.
    It has to do with what applescript is designed for, mainly specific task you are hoping to automate and not stay open monitoring etc. As for asking why Applescript can't detect ShiftDown you need to define your terms a little better. System Events can't detect ShiftDown, but can trigger keystrokes from within applescript, and there are extensions that can detect shiftdown which could be called from an applescript.
    In this case, when launched/clicked, the script opens a Finder windows of a certain size at the bottom of the screen. If the ShiftKey is down when launched/clicked, it opens a smaller window at the top of the screen.
    Is there another way to do this without having two AppleScript apps in the dock?
    thanks

  • Recognizing multiple key presses in As3

    Hi,
    I have a simple game with three keyboard inputs - left, right and fire
    I want to be able to log when a key is pressed and released. In the game, you can be in the following states:
    None
    Left only - keyz on the keyboard
    Right only - keyc on the keyboard
    Fire only - keyx on the keyboard
    Left and Fire - keyz and Keyx on the keyboard
    Right and Fire - Keyc and Keyx on the keyboard
    When Left key is pressed for example, it should log LeftKeypressStart and when it is released, it shoul log leftKeyPressStop. The same should happen to Right and Fire keys when they are pressed individually.
    Now, for the game to be in  Left and Fire state either of the three conditions are true:
    Left key can be pressed and held down before the fire button is pressed and held down or
    Fire button is pressed and held down before left is pressed and held down or
    Both keys pressed down simultenuosly (although this condition will rarely occur as we are not robots)
    Similar conditions should be true for the game to be in the Right and Fire State
    Now considering the first condition,when Left key is down, I want the game to log LeftKeypressStart but as soon as the Fire key is down, it should log LeftKeyPressStop and also Log LeftandFireKeypressStart. Then if Fire is released first, I want it to log LeftandFirKeypressStop and then log LeftKeyStart. but if Left is released first, it should log  LeftandFirKeypressStop and then lof FireKeyPressStart.
    This is what I have at the minute:
    private function onKeyPress (evt:KeyboardEvent)
    if (evt.keyCode == 67 && evt.keyCode !=88 && evt.keyCode != 90)
    //log Right  
    else if (evt.keyCode != 67 && evt.keyCode !=88 && evt.keyCode == 90 )
    //log Left
    else if (evt.keyCode != 67 && evt.keyCode !=90 && evt.keyCode == 88)
    //log Fire
    else if (evt.keyCode == 67 && evt.keyCode !=90 && evt.keyCode == 88 )
    //log RF
    private function onKeyRelease(evt:KeyboardEvent)
    if (evt.keyCode == 67 && evt.keyCode !=88 && evt.keyCode != 90)
    //stop right
    else if (evt.keyCode != 67 && evt.keyCode !=88 && evt.keyCode == 90 )
    //stop Left
    else if (evt.keyCode != 67 && evt.keyCode !=90 && evt.keyCode == 88)
    //stop Fire
    else if (evt.keyCode == 67 && evt.keyCode == 88  && evt.keyCode !=90 )
    // stop RF    

    There can only be one evt.keyCode per keypress, so your approach will not work.  All you need to do is determine which key caused the function to execute.  If you want to keep track of which keys are down, just create three Boolean variables, as in...
    var leftDown:Boolean = false;
    var rightDown:Boolean = false;
    var fireDown:Boolean = false;
    and set those values to true or false and make use of them in whatever other code you intend.
    private function onKeyPress (evt:KeyboardEvent)
    if (evt.keyCode == 67)
                 rightDown = true  
    else if (evt.keyCode ==88)
                 leftDown = true
    else if (evt.keyCode == 88)
                 fireDown = true
    // process per whatever values are true/false
    and in the key up function set them back to false in a similar fashion.

  • I like the "whites" and "blacks" sliders in lightroom with the option key pressed- is there a corresponding slider in aperture? thank you

    i like the "whites" and "blacks" sliders in lightroom with the option key pressed- is there a corresponding slider in aperture? thank you

    There's no exact analogue to the "whites" slider in Aperture.  But you could do it with curves if you wanted.  You can set the white point using the curves tool as well.

  • IPhoto opens but then the spinning rainbow wheel appears and I can't do anything. I have opend iPhoto with the Option key pressed and rebuilt the library and it still happens.  I want to at least access my photos and copy them to an external drive.

    iPhoto opens but then the spinning rainbow wheel appears and I can't do anything. I have opend iPhoto with the Option key pressed and rebuilt the library and it still happens.  I want to at least access my photos and copy them to an external drive. Anyone have ideas on how to get to them?

    Make a temporary, backup copy (if you don't already have a backup copy) of the library and try the following:
    1 - delete the iPhoto preference file, com.apple.iPhoto.plist, that resides in your
         User/Home()/Library/ Preferences folder.
    2 - delete iPhoto's cache file, Cache.db, that is located in your
         User/Home()/Library/Caches/com.apple.iPhoto folder. 
    Click to view full size
    3 - launch iPhoto and try again.
    NOTE: If you're moved your library from its default location in your Home/Pictures folder you will have to point iPhoto to its new location when you next open iPhoto by holding down the Option key when launching iPhoto.  You'll also have to reset the iPhoto's various preferences.
    OT

  • Help with  On key press and Frame

    Hi everybody,
    I have been trying to make this work but not able to. It would be of great help if u can tell where i am going wrong. Here is my code ( it is prety small) :
    I am trying to draw a random line when i do a keypress on the text field.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class KeyPress extends Frame{
    Label label;
    TextField txtField;
    public static void main(String[] args) {
    KeyPress k = new KeyPress();
    public KeyPress(){
    super("Key Press Event Frame");
    Panel panel = new Panel();
    label = new Label();
    txtField = new TextField(20);
    txtField.addKeyListener(new MyKeyListener());
    add(label, BorderLayout.NORTH);
    panel.add(txtField, BorderLayout.CENTER);
    add(panel, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent we){
    System.exit(0);
    setSize(400,400);
    setVisible(true);
    public class MyKeyListener extends KeyAdapter{
    public void keyPressed(KeyEvent ke){
    char i = ke.getKeyChar();
    String str = Character.toString(i);
    label.setText(str);
    Line2D myLine = new Line2D.Double(5,5,100,100);
    }

    Here's what I come up when I played with your code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Random;
    public class KeyPress extends Frame {
        TextField txtField;
        Panel panel;
        public static void main(String[] args) {
            KeyPress k = new KeyPress();
        public KeyPress(){
            super("Key Press Event Frame");
            panel = new myCanvass();
            txtField = new TextField(20);
            txtField.addKeyListener(new MyKeyListener());
            panel.setBackground(Color.LIGHT_GRAY);
            add(txtField, BorderLayout.PAGE_END);
            add(panel, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent we){
                    System.exit(0);
            setSize(400,400);
            setVisible(true);
        class myCanvass extends Panel {
            private Graphics2D g2;
            public void paint(Graphics g) {
                drawLine(g);
            private void drawLine(Graphics g) {
                g2 = (Graphics2D) g;
                g2.setColor(Color.RED);
                g2.draw(new Line2D.Double(Math.random() * 150, Math.random() * 150, Math.random() * 200, Math.random() * 200));
        class MyKeyListener extends KeyAdapter{
            public void keyPressed(KeyEvent ke){
                char i = ke.getKeyChar();
                String str = Character.toString(i);
                panel.repaint();
    }

Maybe you are looking for