Help with key event

hi everyone i need some help. i have to write an java application thatcreates a panel with three labels and three key events to call upon different methods. i try to creat a JFrame but have problems. anyone can help?
Thanks

public class MyClass extends JFrame{
public MyClass(){
getContentPane().add( new Label("One") );
getContentPane().add( new Label("Two") );
getContentPane().add( new Label("Three") );
setSize(400,400);
setVisible(true);
public static void main(String[] args){
MyClass myclass = new MyClass();
public static void main is the starting point of a program.
When the frame is created using
MyClass myclass = new MyClass();
The control goes to the constructor where you can add three labels.
You can add three methods to MyClass and implement KeyListener in MyClass to build upon it.

Similar Messages

  • Help with Keyboard Event

    Hi, I am designing a drum machine in flash pro Cs6 actionscript 3.0  and I am trying to add a keyboard event that will trigger a button event that I have all ready created, I can create the event to play the sound but this is not what I want, can I call the click event so the button will move on the key event triggering the sound, here is an example of one of my buttons code... btn, thank you if anyone can help.
    import flash.events.KeyboardEvent;
    playsound2.fla
    playsound with extra functionality:
    textbox added.
    Displays ID3 info of the sound
    btn.addEventListener(MouseEvent.CLICK, playSomeSound);
    function playSomeSound(e:MouseEvent)
              var req:URLRequest = new URLRequest("Savage.mp3");
              var s:Sound = new Sound(req);
              s.addEventListener(Event.COMPLETE, onSoundLoaded);
              s.addEventListener(Event.ID3, onID3Info);
    function onSoundLoaded(event:Event):void
              var localSound:Sound = event.target as Sound;
              localSound.play();
    function onID3Info(e:Event):void
              var id3Props:ID3Info = e.target.id3;
              var sOut:String = txt.text = "";
              for (var propName:String in id3Props)
                        sOut = propName + "=" + id3Props[propName] + "\n";
                        trace(sOut);
                        txt.appendText(sOut);
              txt.text = id3Props.comment;
    var ba:ByteArray = new ByteArray();
    var gr:Sprite = new Sprite();
    gr.x = 5;
    gr.y = 50;
    addChild(gr);
    var time:Timer = new Timer(50);
    time.addEventListener(TimerEvent.TIMER, timerHandler);
    time.start();
    function timerHandler(event:TimerEvent):void
              SoundMixer.computeSpectrum(ba, false);
              var i:int;
              gr.graphics.clear();
              gr.graphics.lineStyle(2, 0xFF0000);
              gr.graphics.beginFill(0x00ff00);
              gr.graphics.moveTo(10, 10);
              //  draw a circle.;
              var w:uint = 15;
              for (i=0; i<512; i+=w)
                        var t:Number = ba.readFloat();
                        var n:Number = (t * 200);
                        gr.graphics.drawCircle(i, 0, -n);

    Thanks, this was the code I added in the end and it works nicely, It covers my sound and id3 aswell as Im displaying lcd text in a dynamic text box.
    stage.addEventListener(KeyboardEvent.KEY_DOWN, btndownKey);
    function btndownKey(event:KeyboardEvent)
              if (event.keyCode == 83)
                        var url:String = "Savage.mp3";
                        var request:URLRequest = new URLRequest(url);
                        var s:Sound = new Sound();
                        s.addEventListener(Event.COMPLETE, completeHandler);
                        s.addEventListener(Event.ID3, onID3Info);
                        s.load(request);

  • Object Movement with Key Events

    Hi everybody!
    Im trying to move an object over the screen with keyboard buttons. The problem I have come across with is that I would like to use the right button to move right, up button to move forward, etc. but I cant push, for example, right and up buttons at the same time to make a diagonal movement. How can I solve this?
    Thank you and regards.

    I added key events to a sequence and than check them in the program.
    Something like this:
    class Car extends CustomNode {
        var keys:KeyCode[];
        public override function create(): Node {
            ImageView {
                transforms: [ Translate{ x: bind x, y: bind y }, Rotate{ angle: bind direction}]
                x: -w
                y: -h
                image: Image { url: "{__DIR__}car.png"}
                onKeyPressed: function( e: KeyEvent ) {
                    insert e.code into keys;
                    if(e.code == KeyCode.VK_UP){
                        ds = 2.0;
                    }else if(e.code == KeyCode.VK_DOWN){
                        ds = -2.0;
                    }else if(e.code == KeyCode.VK_LEFT){
                        da = -1.0;
                    }else if(e.code == KeyCode.VK_RIGHT){
                        da = 1.0;
                onKeyReleased: function( e: KeyEvent ) {
                    delete e.code from keys;
        public function move(){
              // check keys
    }

  • Help with combobox event handling

    hey techies
    does knw any1 tutorial or where any URL which helps me adding event handling to combobox
    iam new at event handling
    i tried
    jc1.addItemListener(this);
    public void itemStateChanged(ItemEvent event)
              if(event.getSource()==jc1)
              System.out.println("hello");
         }is this way correct to specify event handling in combobox
    i tired this iam getting NPE like this
    Exception in thread "main" java.lang.NullPointerException
    at FinalMobile.<init>(FinalMobile.java:213)
    at FinalMobile.main(FinalMobile.java:740)
    plz jst let me knw and dnt tell me to refer swing tutorial i have been reffering it
    any help is appreciated

    does knw any1 tutorial or where any URL which helps me adding event handling to comboboxExcuse me, I've told you at least 4 times now to download and read the Swing tutorial which has all this information with working examples. I even provided you with the download link.
    How do you have the nerve to say you can't find any tutorial?

  • Probelm with key events

    Hi all
    I am trying to open a swing form from a menu on a Frame object
    On the frame I have a Canvas3D
    everything is going well the canvas3d read my key events and I can walk gladly in my universe
    untill I am opening JFrame and do some stuff on it (changeing values in text fields)
    Hiding the Jframe and trying to keep moveing in my universe is not working any more any ideas???

    I checked it more closly and found out that the I do get the events and the behvior do act on them but I see nothing on the screen help....

  • First Mac-need help with an "event"

    Hi:
       After 3 days of busy activity with no freeze ups, I was feeling pretty confident.  However, late last night I ran into an "event" that eventually required me to reload Tiger.
       (1) I was working along and for some reason, clicking my mouse did not have any effect on any of the programs--either those running or attempting to start new ones.  
       (2) I was able to tab through those programs running and with a command-Q quit out of those running...still no effect on any mouse clicks....no problem moving the mouse and it would highlight top left corner buttons, but no effect if I attempted to minimize or exit.
       (3) I shut the computer off and restarted a number of times....came up to the same screen each time.    Held the off button both in shutting down and starting up and this time it would go to the log on screen where I was able to type in my password.  Would come up to the same screen as I left it.
       (4) Was able to use the remote control just fine to look at pictures, etc.
       (5) After some reading, did a PRAM reset....same story as above.
       (6) Finally reloaded a new copy of Tiger and was back in business.
    Questions:
      (1) Is this the typical freeze people are getting....with PCs, when it freezes, nothing moves and when you reboot, you have a fresh start?
      (2) Short of reloading Tiger, if this happens again, what remedy (other than sending my new iMac back!) would you suggest?
    Thanks for your help!

    Many thanks for the suggestion and the giving me some hope that this is not the dreaded freeze issue!
    I forgot to mention perhaps one important bit of information: There were two Finder "windows" that were present when my "event" occurred and each time I rebooted, these same two Finder windows reappeared and my mouse was unable to move them or close them or execute any command line operations.
    Not sure if this changes the story about it being a mouse software related error or not, but I found it strange that on hard reboots the machine came back with the same two windows of information.

  • Need help with Buttons/Events

    HI
    Here is what I am doing. I am creating an "operations"
    calendar for my workplace. So far I have been successful with
    creating the page, inserting links, tags, images etc.....
    But now I want to add an Event button - where once the button
    is clicked - it will launch a script on my UNIX server.
    Cant quite figure this one out
    Any help would be greatly appreciated

    Hey man, I 've done some correction, and it seems work, why don't you try the code to see if it is what you want.
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    public class ComplexMenu11 extends Applet implements ActionListener {
    Button open, close;
    MenuFrame f;
    public void init() {
    open = new Button("Open");
    add(open);
    open.addActionListener(this);
    close = new Button("Close");
    add(close);
    close.addActionListener(this);
    f = new MenuFrame("A Complex menu");
    f.setSize(200, 200);
    f.show();
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() == open) {
    if(f.isShowing())
    f.show();
    }else{
    if(!f.isShowing())
    f.hide();
    class MenuFrame extends Frame implements ActionListener{  //and implements here too
    Font font;
    Label l;
    int fontsize;
    //MessageDialog md;
    MenuBar mb = new MenuBar();
    Menu m1 = new Menu("Colours");
    MenuFrame(String name) {
    super(name);
    m1.add(new MenuItem("White"));
    m1.add(new MenuItem("Light grey"));
    m1.add(new MenuItem("Yellow"));
    Menu m2 = new Menu("Font");
    m2.add(new MenuItem("10"));
    m2.add(new MenuItem("12"));
    m2.add(new MenuItem("14"));
    m2.add(new MenuItem("16"));
    m2.add(new MenuItem("18"));
    m2.add(new MenuItem("Message"));
    mb.add(m1);
    mb.add(m2);
    setMenuBar(mb);
    m1.addActionListener(this); //Add listener here
    l = new Label("A frame demonstration", Label.CENTER);
    add("South", l);
    //md = new MessageDialog(this,"Name",true);
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() instanceof MenuItem) {
    //fontsize = 18;
    String label = evt.getActionCommand();
    if(label.equals("White")) {
    //setBackground(Color.white);
    System.out.println("This is the white point");
    }

  • JTree traversal with key events

    I am looking for any classes available for traversing nodes in Jtree based on the input given through keyboard matching with nearest name in the tree being displayed. This is similar to the feature we have in windows explorer where based on the name we type it selects the nearest node in the tree taking into consideration the expanded paths.
    Thank you in anticipation,
    Srikanth

    What exactly you want to do.
    Have a look at my code, this is what I did a while ago. This may a good start for you.
    tree.addKeyListener(new java.awt.event.KeyAdapter() {
             public void keyPressed(KeyEvent e) {
                tree_KeyReleased(e);
        * JTree Key Released Functionality
        * @param e KeyEvent
       private void tree_KeyReleased(KeyEvent e) {
          try {
          MouseEvent me = new MouseEvent(tree, MouseEvent.MOUSE_RELEASED, 0, 0, 0, 0, 0, false);
          int keyCode = e.getKeyCode();
          // Get the Tree Path
          TreePath selPath = tree.getSelectionPath();
          if (keyCode == e.VK_DELETE) { //KeyCode - 127
             removeSelectedNode();
          else if (keyCode == e.VK_ADD) { // Key Code - 107
             tree.expandPath(selPath);
          else if (keyCode == e.VK_SUBTRACT) { // Key Code 109
             tree.collapsePath(selPath);
          else if (keyCode == e.VK_ENTER) {
             tree_mouseReleased(me);
          else {
          } catch (NullPointerException ex) {
          //System.out.println("Null");
       }

  • Need help with custom event from Main class to an unrelated class.

    Hey guys,
    I'm new to Flash and not great with OOP.  I've made it pretty far with google and lurking, but I've been pulling my hair out on this problem for a day and everything I try throws an error or simply doesn't hit the listener.
    I'm trying to get my Main class to send a custom event to an unrelated class called BigIcon.  The rest of the code works fine, it's just the addEventListener and dispatchEvent that isn't working.
    I've put in the relevant code in below.  Let me know if anything else is needed to troubleshoot.  Thank you!
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                placeIcons();
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 4; i++)
                    for (j = 0; j < 5; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i,j);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
            function twitchUp(e:Event)
                this.y +=  10;

    Ned Murphy wrote:
    You should be getting an error for the Main.as class due to missing a line to import the Event class...
    import flash.events.Event;
    My apologies, I should attempt to compile my example code before I ask for help...
    Alright, this compiles, gives me no errors, shows my 'book' and 'flowers' icons perfectly when ran, and prints 'addEventListener' to the output window as expected.  I get no errors when I press the button, 'dispatchEvent' is output (good), but the 'twitchUp' function is never called and 'EventTriggered' is never output. 
    How do I get the 'twitchUp' event to trigger?
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import flash.events.*;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            var iconString_array:Array = new Array(2);
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                buildStringArray();
                placeIcons();
            function buildStringArray():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    iconString_array[i] = new Array(3);
                    for (j = 0; j < 3; j++)
                        if (Math.random() > .5)
                            //'flowers' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "flowers";
                        else
                            //'book' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "book";
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    for (j = 0; j < 3; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i*50,j*50);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
                trace("dispatchEvent");
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.*;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
                trace("addEventListener");
            function twitchUp(e:Event)
                this.y +=  10;
                trace("EventTriggered");
    Output:
    [SWF] Untitled-1.swf - 40457 bytes after decompression
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    dispatchEvent
    [UnloadSWF] Untitled-1.swf
    Test Movie terminated.

  • Help with the event log in the type B hub

    I have  probs with broadband slowing down and also with link going down a number of times again (it recovers quickly)
    I just wanted to confirm that the message in trhe event log in the type B hub:-
    (134558.700000) RTNL: Received ERROR reply 'No such process' for message type 0x19
    was the link dropping.
    Can anybody confirm this and does anyone know if/where the messages are documented?
    Thanks in advance
    Banz

    does nobody have any comments on this
    Mods - please help
    banz
    ps this is my last bump - I will give up after this

  • Help with Keys in Map

    Hi All,
    I have a Map and I want to add entries - Key and Value. Now the Key is an Object (Some Object Key which has some instance variables). When I try to add the Key and Value only one entry gets stored. I know I am doing something Wrong.
    class Key {
    private Date time;
    private long someNumber;
    public Key(Date time, long someNumber) {
    Any help would be appreciated
    Thanks
    --J                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I am using TreeMap and I am unable to add to
    diffferent instances of Key in the MapWhat do you mean different instances?
    Thousands of developers are using Maps in Java every day. There's nothing wrong with it. If there's a problem, it's something you are doing.

  • Help with NSButton event

    Hi,
    I have a problem: I want to place a NSButton with type of "Recessed Button" on NSView and part of button should be on view and another part should be outside of this view
    That's ok, but when cursor of mouse move inside button and outside view, button receive event about this.
    What need to do for this event do not send to button when cursor move outside my view ?
    Thanks

    I think that if replace options in NSTrackingArea for NSButton it will be help me
    In Debugger I saw that default options is 4225 - I think that it's NSTrackingMouseEnteredAndExited|NSTrackingActiveAlways|NSTrackingAssumeInside
    I want replace it to NSTrackingMouseEnteredAndExited|NSTrackingActiveAlways|NSTrackingInVisibleRect
    But if I do it in awakeFromNib function and add breakpoint in drawRect: -- it have first value. Somewhere value overwrite before drawRect:
    Code:
    //MyButton.mm
    - (void)awakeFromNib
    NSArray *a = [self trackingAreas];
    NSTrackingArea * t = [[NSTrackingArea alloc] initWithRect:(NSRect){0, 0, 100, 50}
    options:NSTrackingMouseEnteredAndExited|NSTrackingActiveAlways|NSTrackingInVisi bleRect
    owner:self
    userInfo:nil];
    [self removeTrackingArea:[a objectAtIndex:0]];
    [self addTrackingArea:t];
    [t release];
    - (void)drawRect:(NSRect)aRect
    NSArray *a = [self trackingAreas];
    NSTrackingArea *t1 = [a objectAtIndex:0]; //always first value !!!
    [super drawRect: aRect];
    Any idea how to do that ?
    Message was edited by: pavelmagur

  • Help. Key Event. Gui.

    hi guys, i have a small problem. i have a form with textfields and buttons... there are two buttons particularly labeled "Enter" and "Cancel".
    how do i activate the "Enter" by pressing the carriage return key while the cursor is in another component, like the textfields.

    ...here are two buttons particularly labeled "Enter" and "Cancel".
    how do i activate the "Enter" by pressing the carriage return key while the
    cursor is in another component, like the textfields.simple demo, provided the textfields do not have an actionListener added to them
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JTextField tf = new JTextField(5);
        JButton btn = new JButton("Enter");
        JFrame f = new JFrame();
        f.getContentPane().add(tf,BorderLayout.CENTER);
        f.getContentPane().add(btn,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        f.getRootPane().setDefaultButton(btn);//<-----------------
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            System.out.println("button clicked");
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Help with the event of closing of fill-out form

    Hi:
    I am in need of his help, I want to grab SAP's event of impression BO, but specifically upon the assignment of folio, this since I want to create a small routine that you not leave behind to enter null values or zero, however when I press the button to close [X] in the fill-out form, this just the same assigns a value zero or void within the data base.
    That way than that you may help oneself with this I will be very grateful
    Greetings Luis

    Luis,
    The forum that you have posted your question in is for questions related to the SAP Business One Integration for SAP NetWeaver.  Is your question related to this product?
    Eddy

  • Help with key issues

    Im developing a backup file system for LANs in Java
    Presently the client encrypts all files with the DES algorithm using the same key before sending them to a server. The key is generated the very first time the software is installed and stored in a file key.txt. All subsequent files will get encrypted using the key from this file.
    The server keeps a record of which files(encrypted) it is holding for which client. The server obv does not keep the encryption key.
    In my system, I want to implement a "Restore" system in which the client should be able to retrieve all his backed up files even if his entire HDD crashes. For this when the client comes up and the software is reinstalled, the user can command the software to start restore. The client searches the LAN for servers that may be holding its files (each computer on LAN will be identified through a unique user name) and retrieves them one by one.
    Problem: Since the key.txt file is also lost because of HDD crash, the client will not able to decrypt the files for the user. Any suggestions on what can be done to address this issue? Does Java provide a way by which it always returns the same key given a username (string)?
    Many thanks for your help
    Message was edited by:
    aybhave

    Check out PBE. A snag would be that if I then knew the user name then I would know the key!

Maybe you are looking for

  • My ON OFF button

    My ON OFF button on the phone does not work. And my phone is warranted. What should I do?

  • Document class Error #2136

    Hi, in Flash CS3 I've this DocumentClass: package {     import flash.display.MovieClip;     public class DocumentClass extends MovieClip {         public function DocumentClass() {             trace("document class created"); This actually works, but

  • 928 Camera - Yellowish Tint When Using Flash

    I find that when I take pictues in lower light situations and use the flash there is a distinct yellowish tint to the picture. I have had better results not using the flash at all. Kind of defeats the purpose of the flash. The pictures were taken usi

  • How to watch .avi video in iphone?

    Hi I use win Vista and I just bought a new iphone. Everything works well. Only one question is : how to watch .avi video in iphone. I download a lot of video in that format but cannot add them into intunes, therefore cannot sync into iphone. I search

  • UDF having date and timezone field in OIM 11gR2

    Hi Experts, How to create UDF having date and time filed in OIM11gR2? Thanks, Amit Edited by: 955130 on Dec 13, 2012 12:18 AM