Get keyEvents!!

I would like to take the event of the keys "Alt + F4" = "close".
Thanks .

Hi,
You need to register a keyboar action in your frame or internal frame. This example is for a table, but it's the same for another component. I hope it helps!
table.registerKeyboardAction(new ActionListener() {
public void actionPerformed (ActionEvent e) {
save();}
}, KeyStroke.getKeyStroke(KeyEvent.VK_F4, Event.ALT_MASK), WHEN_FOCUSED);
save() is the method I want to perform...
Regards,
aninhas.

Similar Messages

  • How to get keyevents in Jframe

    Hi,
    If i make usual keylistener class for keyevents and
    add it to jframe itself, the frame doesen't get any
    of keyevents. Alltough all buttons and such components
    which has same listener added gets events (when focused).
    The frame itself is allso focused when trying this.
    I tried allso add keylistener to container and all panels
    in that frame, but it had no better effect.
    There must be a way that frame can as get keyevents as default.
    I will be very pleased of any help.

    Are you sure you added a KeyListener to the right component? If you want your frame or panel to receive KeyEvents no matter what child component has the focus (ie. generated the event) then you will need to add a keylistener to every component in the frame (you can use a loop)and just use your frame as the sole KeyListener.
    I am pretty sure that will work but I'm not sure exactly what you have already tried. If that doesn't work then it could be related to the component consuming events. They do consume some events but I thought they would call all of their listeners first.
    Jeff

  • Newbie in Fullscreen Mode need help

    hello
    i am new to writing game in java.
    i used to put component to panel, set Layout, that kind of things, to deal with user response.
    now writing game, a full-screen one, i think of having only a frame and a canvas that draw the whole
    output. i think this is probably what simple game do. so i have a frame and one canvas in side.
    1. the problem is when i set the frame to full-screen mode, the canvas didn't get to the same size. it has size of zero!! so i can't create BufferStrategy from zero height canvas. how can i solve the problem. well, i can get BufferStrategy from frame and i can draw directly to the frame, not to the canvas.but is it the way it suppose to be? shouldn't i draw to something like canvas?
    2. second problem is that, with no Component in full-screen frame, i Don't get KeyEvent at all !!!! how can someone play Quake without keyboard???
    please help me out.

    I took Frame. After all Frame is a Component. So you can get KeyEvents.

  • Canvas3D problems

    Im having a few problems with canvas3d.
    1) I have an applet that uses a single JPanel with a canvas3d object in it. When I click the applet to focus it, my jpanel gets keyevents and mouse events, but if i click on the canvas3d, it no longer receives keyevents, but will still receive mouse events. I end up having to click outside of the applet then back inside it to refocus.
    2) to remedy the above problem, I tried to render the canvas 3d object offscreen and 'screenshot' it, then render the image from that in the panel, which works but, when you make a canvas 3d offscreen there is a black space where the canvas should be, and if you click on that, you still have the same problem from 1).
    3) lastly, setBounds and setLocation for my canvas3d isnt changing its location on the screen at all, the canvas stays in the same place no matter what i enter there.
    Any help would be appreciated. I wasnt quite sure which code snippets would help, so I didnt post any.

    Heres the constructor for the panel class:
         public MyPanel()
              //2d init stuff
              this.setDoubleBuffered(false);
              this.setBackground(clear);
              this.setPreferredSize( new Dimension(PWIDTH, PHEIGHT));
              this.setFocusable(true);
              this.requestFocus();
                 this.setOpaque( true );
                loadImages();
             //3d init stuff
             canvas3D = new Canvas3D(config);
             canvas3D.setFocusable(false);
              canvas3D.setBounds(11,11,388,338);
              this.add(canvas3D);
              sceneBG = createSceneGraph();
              sceneBG.compile();
             su = new SimpleUniverse(canvas3D);
              su.getViewingPlatform().setNominalViewingTransform();
             su.addBranchGraph( sceneBG );
         } // Budria3dPanel()Everything works and the cube is displayed and rotates, but I cant get the canvas to move, its always in the center of the screen, no matter what I set the bounds to, even if I use setLocation. Im still working on the key event problem, but if I could fix this, then I probably wont need to fix the key problem.

  • Java and Networks - questions

    Hi,
    I have this idea in my head, and i wanna get it out..
    Okie the plan is that I want to create something like a macro program. The special thing is that I want to create a server and 2 clients. The thing I want is that whenever I hit a special key from Client1, that key is going to be sent to the server,then the server is going to modify it, and then send to the Client2. And then the Client2 will invoke the key just like a macro program.
    Okie the networking part, I kindda have an idea what how to do it. However since it is more like a macro program, I want it (client/server) to run simutaniously with other programs I am running.
    Ex:
    Let's say I am playing a game, I hit number 1 to signal the game that I want my unit to attack something. Meanwhile the Client gotta capture the key 1 that I just hit and send it to the server and then the client2, and then perform an action of pressing a key that a server sends to.
    Could anyone have an idea of how to do the capture keys and invoke keys as I mentioned above?
    Thank you
    please email me at [email protected] if you could help me out

    JNI (Java Native Interface) is the interface between Java and C (usually native functions in C). In C you can do a lot more low-level stuff than in Java, particularly interacting with the OS at a system level. This is the native part.
    Ie, the system knows about all key events. It then sends them to the OS, that only directs them to the program with focus. (Might be java, might not. But no program can get keyevents intended for another program).
    Using JNI, you could intercept the keyevents betweent the system and the os, and do what you want with them.
    But, I don't know JNI, and I don't know much about it. This is mainly guesswork. It's along the right track, but the system/os stuff might not be 100% correct.
    The other thing is, once you start writing code that interacts directly with the system, it loses all cross-platform compatibility. IE, if you write something that interacts with windows, it obviously won't work on Linux.
    Cheers,
    Radish21

  • Using gridBagLayout

    I am currently developing a program using gridBagLayout. I am having problems getting the events to work correctly. I have noticed that events only seem to work with a class extending JPanel, and GridBagLayout needs to be written in the class that is extending JFrame.
    I have tryed various ways of writing the program so that I have 2 classes. One implements JPanel and one implementing JFrame, but when I do that I loose all of by buttons and text fields.
    Which parts of GridBagLayout need to be in the JFrame class and which ones can go in the JPanel class so that I can get my events working for my buttons and textfields?

    When I add in my action events they don't work.
    and Now I am working on getting keyevents to work with my buttons . . here are the functions that do not work and an explaination of what is missing. This program thus far is over 400 lines long
    class someClass extends JFrame implements ActionListener, KeyListener
    { final boolean shouldFill = true;
    final boolean shouldWeightX = true; // Some strange true false things
    public someClass()
    { setTitle("Some title"); // the title at the top of the window
    setSize(750, 500); // the size of the window in Pixels
    addWindowListener(new WindowAdapter() // Make sure the window
    { public void windowClosing(WindowEvent e)  //closes and the
    { System.exit(0);         // Program exits instead of
    } // Just hiding
    // This is the setup for implementing gridbaglayout
    // It has to go right here or this program will not work correctly
    Container contentPane = getContentPane(); // Initialize the container
    GridBagLayout gridbag = new GridBagLayout(); // Intitialize the GridBagLayout manager
    contentPane.setLayout(gridbag); // Put the gridbag inside the contentPane
    GridBagConstraints c = new GridBagConstraints(); // Initialize the constriants
    this is just the implimentation of my buttons and such
    //ActionListeners go here
    DoneButton.addActionListener(this);
    RejectPartButton.addActionListener(this);
    AcceptPassButton1.addActionListener(this);
    AcceptPassButton2.addActionListener(this);
    AcceptPassButton3.addActionListener(this);
    RejectPassButton1.addActionListener(this);
    RejectPassButton2.addActionListener(this);
    RejectPassButton3.addActionListener(this);
    serialSize.addActionListener(this);
    // I guess I'll put some KeyListeners here. this program needs them as well
    DoneButton.addKeyListener(this);
    RejectPartButton.addKeyListener(this);
    AcceptPassButton1.addKeyListener(this);
    AcceptPassButton2.addKeyListener(this);
    AcceptPassButton3.addKeyListener(this);
    RejectPassButton1.addKeyListener(this);
    RejectPassButton2.addKeyListener(this);
    RejectPassButton3.addKeyListener(this);
    serialSize.addKeyListener(this);
    // Now every button also has a key listener
    // Events are implemented differently in Swing than they were previously and
    //They are implemented differently from that when you use GridBagLayout
    public void actionPerformed(ActionEvent Aevent)
    { Object source = Aevent.getSource();
    Color color = getBackground();
    if (source == DoneButton)
    { color = color.red;
    else if (source = RejectPartButton)
    { color = color.blue;
    else if (source = AcceptPassButton1)
    { color = color.green;
    setbackground(color);
    repaint();
    // Let's toss in those KeyListener things here
    public void KeyPressed(KeyEvent Kevent)
    { int KeyCode = Kevent.getKeyCode();
    int modifiers = Kevent.getModifiers();
    if ( KeyCode == KeyEvent.VK_ENTER || KeyCode == KeyEvent.VK_TAB)
    { serialSize.requestFocus();
    else { transferFocus();
    public static void main(String[] args)
    { JFrame frame = new Norton3();
    frame.show();
    private JButton DoneButton;
    private JButton RejectPartButton;
    private JButton AcceptPassButton1;
    private JButton AcceptPassButton2;
    private JButton AcceptPassButton3;
    private JButton RejectPassButton1;
    private JButton RejectPassButton2;
    private JButton RejectPassButton3;
    private JTextField serialSize;
    } // end of some class
    // Looks like this is the end of the program

  • HListGroup and HItemEvents

    Hi all,
    How do I get HItemEvents out of an HListGroup?
    I can get KeyEvents by adding KeyListener functions
    and then do my own element navigation.
    But I can't figure out what I need to enable to get the
    translated HItemEvents and automatic element navigation.
    I've called setEnabled(true) and setSelectionMode(true).
    Ideas?
    Thanks,
    -troy

    hi
    with what kind of tool to you view your Xlet? or are you using STB?
    if you are using openMHP or xletview, please check that HListGroup and HListElement classes are fully implemented.
    regards

  • KeyEvents  getting buffered

    Hi All,
    I am facing the following problem :
    My midlet makes a network connection and while the connection is being made, I make the midlet paint a small rectangle and image frames to show some "animation" going.
    Now when the Animation and Network connection are going on, any "key pressed" is getting "buffered".
    That is if you press any key during animation & network connection, My keypresed( ) is not getting called...Rather once the animation is over, my keypressed is called for all the keys pressed during the connection.
    I am doing the network connection in different thread, but paint and keypressed are in same class...and I dont want to keep them apart.
    Is there anyway I can clear the keyEvent's queue that is holding the keys.

    Is your animation running in a separate thread? If not try to put it in one. My experiance is that the "main"-thread is used to basically everything so it is a good practise to not block it , so it usually worth the extra work of spawning a new thread.
    Regards
    Roland Carlsson

  • How to get the caret inside a custom editor?

    I was reading through old posts the other day and noticed this by Rob Camick in this thread Re: Problem in cell selection in JTable Java Swing :
    camickr wrote:
    All KeyEvents are passed to the editor for the cell and the editor is psuedo invoked. That is, the caret is not placed on the text field used as the editor, but the character typed is added to the editor.This set me thinking about a known issue in my app which I had shelved for a "rainy day": how to get the caret into the cell editor component. I thought I'd get it out and look at it. I tried the following, in my custom cell editor:
      public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
                                                 int row, int column)
        JTextField ec = (JTextField) editorComponent;
        ec.setText((String) value);
        if ("".equals(ec.getText()))
          ec.setCaretPosition(0);
        else
          ec.selectAll();
        return editorComponent;
      }But it has no effect whatsoever, the user still can't type something in and then press the backspace key to useful effect. Has anyone out there solved this problem? (And why, oh why, is the caret not put into the cell editor by default, if it's a component that has a caret?)

    Replying to my own post, in case what I ended up with is of some help to others. The desired behaviour was that anything the cell contained from the previous edit would be replaced by what the user types in the current edit, i.e.:
    user starts edit, types 234, stops editing, cell displays 234...user single-clicks on cell, types 567, stops editing, cell displays 567
    My code is as follows:
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row,
                                                     int column)
          final JTextField ec = (JTextField) editorComponent;
          ec.setText((String) value);
          // selectAll, so that whatever the user types replaces what we just put there
          ec.selectAll();
          SwingUtilities.invokeLater(new Runnable()
            public void run()
              // make the component take the keyboard focus, so the backspace key works
              ec.requestFocus();
              SwingUtilities.invokeLater(new Runnable()
                public void run()
                  // at this point the user has typed something into the cell and we
                  // want the caret to be AFTER that character, so that the next one
                  // comes in on the RHS
                  ec.setCaretPosition(ec.getText().length());
          return editorComponent;
        }

  • KeyEvents with the TAB Key

    Hey All,
    I have a small progam with a small problem. My program is an applet with numerous textfields and I have implemented the KeyEvents event listener. What I want to have happened when I press the "Tab Key" is the cursor move from one tab to another, but when it goes to the next tab it clears out the text that is currently in the textfield. Take a look at my code segment that is giving me the problem.
    public void keyPressed(KeyEvent e)
    if(NameField == e.getSource())
              if(e.getKeyCode() == KeyEvent.VK_TAB)
                   SalaryField.setText(" ");
    I know that is works if I replace "VK_TAB" with something else like "VK_A". "NameField" and "SalaryField" are the names of mt textfields. I am currently using Java SDK 1.3.1 to program in java program, but my browser uses JVM/Runtime Enviornment 1.4.1. When I run it with my broswer nothing happens when I press tab and some for the program that I am using to progam in. I did a search in the forum and came up with I have above, but still cannot it to work. When I read APIs on 1.4.1 and 1.3.1 that both said that
    "Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future."
    What is going on? How can I solve this problem?
    Thanks,
    Iceman
    PS:
    My Interface is swing

    Hey All,
    Thanks for the help I got to work when I ran it with my programming program, but when I run it in a browser using the current JVM the tab key does not work. What is wrong now? Or how am I to use FocusListener now, I tried to use the getOppositeComponent(, my complier says that it is not a method of FocusListener. Even though java says in the docmentation that it is. Can I get some more help here. The questions again is How can I tab in a applet?
    Later,
    Iceman

  • How to convert a string into a collection of KeyEvents

    I'm working on a program that must interact with a 3rd party application (closed to me, I have no access to the code or anything like that). I have been unable to send data to the program by getting its OutputStream. The only thing that has worked was using a Robot object to send individual key events (i.e. robot.keyPress(KeyEvent.VK_A);). Therefore I'm looking to convert a string (many different strings actually) into a collection of their associated KeyEvents so I can send them to the other application. Does anyone know a good way of doing it, or is anyone able to help me with using the OutputStream?
    Thank you!
    (The 3rd party application is Attachmate InfoConnect, a Unisys terminal emulation program that I have to use to access a mainframe).

    Here is a code sample.     public void checknumber(int vsize){
    int total;
    String anum;
    anum = tf2.getText();
    validnumber = true;
    lines2combine = 1;     //default (an integer)
    recs2make = 1;          //default
    try{
    lines2combine = Integer.parseInt(anum);
    catch (NumberFormatException e){
              System.out.println("Entry for lines to combine not numeric");
         validnumber = false;
         d1Title = "Data Entry Error";
         d1Txt = "For number for lines to combine;";
         d2Txt = "Enter a number.";
         doMessage();

  • Cant get rid of text drawn with drawString, drawString only wrking in paint

    Sorry for coming back to ask for more help, but I just caught a snag that I can't get around.
    As you can see, "Press Space to start..." is drawn during the paint method. When the user presses space, the other KeyEvents are enabled, but filling a black rectangle where the text is does not hide it. If I put the clearText call before the started = false, then the other KeyEvents aren't enabled.
    Also, when I try to draw another string in win method, it doesn't show up.
    You can check out the complete applet at http://users.adelphia.net/~uberugh/Race.html
    This code compiles with no errors but requires Car.java.
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class Race extends Applet implements KeyListener {
         private Car car1;
         private Car car2;
         boolean started = false;
         private Image dbImage;
         private Graphics dbg;
         private Graphics txt;
         private Graphics g2;
         Font f = new Font("Arial", Font.PLAIN, 36);
         Font f2 = new Font("Arial", Font.PLAIN, 12);
         public void init() {
              setBackground(Color.black);
              car1 = new Car(10, 146, Color.green);
              car2 = new Car(10, 246, Color.blue);
              addKeyListener(this);
         public void paint(Graphics g) {
              g.setColor(Color.darkGray);
              g.fillRect(0, 0, 600, 100);
              g.fillRect(0, 300, 600, 100);
              g.drawLine(0, 200, 600, 200);
              g.setColor(Color.yellow);
              g.drawLine(550, 100, 550, 300);
              g.setColor(Color.red);
              g.setFont(f2);
              g.drawString("Press Space to start...", 250, 180);
              car1.drawCar(g);
              car2.drawCar(g);
         public void update(Graphics g) {
              if (dbImage == null) {
                   dbImage = createImage(this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics();
              dbg.setColor(getBackground ());
              dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor(getForeground());
              paint(dbg);
              g.drawImage(dbImage, 0, 0, this);
         public void keyTyped(KeyEvent e) {}
         public void keyReleased(KeyEvent e) {}
        public void keyPressed(KeyEvent e) {
              int k = e.getKeyCode();
              if (k == KeyEvent.VK_SPACE) {
                   started = true;
                   clearText(249, 159, 100, 30);
              if (started) {
                  if (k == KeyEvent.VK_G) {
                       car1.move();
                       repaint();
                       if (car1.winner) {
                            win(1, txt);
                  } else if (k == KeyEvent.VK_RIGHT) {
                       car2.move();
                       repaint();
                       if (car2.winner) {
                            win(2, txt);
         public void win(int x, Graphics g) {
              removeKeyListener(this);
              g.setColor(Color.red);
              g.setFont(f);
              g.drawString(String.valueOf("Player " + x + "wins!") , 200, 218);
              repaint();
         public void clearText(int x, int y, int width, int height) {
              g2.setColor(Color.black);
              g2.fillRect(x, y, width, height);
    }

    That's because you're trying to paint to a null, non-existent Graphics object.
    Your approach is wrong. Don't try to draw when you get the key event, because there may be nothing to draw then anyway (the GUI thread isn't in the act of drawing). Use your event handlers to set internal state of your game object (Race, or other objects as necessary like Car). Then when you draw, use that state. So use your boolean field "started". In your paint method, do this:
    if (!started)
         g.drawString("Press Space to start...", 250, 180);Then just get rid of your cleartext method.

  • Handling KeyEvent (filtering KeyEvents)

    I am writing a code to learn how KeyEvents behaves and how to manipulate and even filtering some events, for example, to filter the normal behaviour of keeping pressed a key that fires a KeyPressed -> KeyTyped -> KeyReleased Events, like pressing the 'a' button, and keeping it pressed, this fires the sequence expressed before as long as the button is keeped pressed.
    From the writing a KeyListener tutorial, (http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html), i've begin to make some tests and changing somethings around the code, but, i am not getting too far as I want to make the 'keeping pressed' behaviour as just one event, the KeyPressed, and only when the user release the key, the KeyReleased Event should be fired.
    In resume, i just want to make any keystroke to be mapped as a modifier key, such as Shift or Control, because i will need a program which only responds with a character to the user, when he releases the key and not just like the KeyTyped Event.
    I am not a programmer, i am just a psychology student who wants to learn about Java programming language and try to apply it to some ideas about how to gather information about the behaviour of people when it's method of interact (virtually) is the keyboard realm.
    Is there anything out there to help me on this trail of learning how to manipulate KeyEvents?
    Thanks in advance, and sorry for the poor english.

    Hi,
    This is a bit of a hack but works nicely. Substitute the keyPressed, KeyReleased and keyTyped methods with the following:
        /** Handle the key typed event from the text field. */
        public void keyTyped(KeyEvent e) {
        //    displayInfo(e, "KEY TYPED: ");
        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            if(key != e.getKeyChar()) {
                displayInfo(e, "KEY PRESSED: ");
                key = e.getKeyChar();
        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            displayInfo(e, "KEY RELEASED: ");
            key = ' ';
        }and declare a char as a class varible like this:
    // ... import statements here
    public class KeyEventDemo extends JPanel
                              implements KeyListener,
                                         ActionListener {
        JTextArea displayArea;
        JTextField typingArea;
        static final String newline = "\n";
        // This is where you'll put the char.
        char key;
        public KeyEventDemo() {
            super(new BorderLayout());
            // ... the rest of the class

  • Wrong characters in KeyEvents generated from input of barcode scanner

    Hi everybody, :-)
    I have a problem with KeyEvents coming from a barcode scanner. The issue seems to have creeped in somewhere between JSE 6u3 and 6u10, as in the former it works as expected and in the latter it does not. The problem persists still, we also tested it with 6u22 and 6u23 (all tests were performed on the same Windows XP machine). The actual test client is very simple, the application is only a JFrame containing a JTextField and a JTextArea.
    The barcode scanner we use connects via USB and has no special driver. The scanner already decodes the barcode that was scanned and "enters" characters in the focussed text field of the test application by emulating the Alt+NumPad behaviour (the character '5' being produced by the equivalent of holding Alt and entering "0053" on the NumPad).
    Now, what appears when the application is run in JSE 6u03 is the expected result:
    5@WM010$|
    5@WM010$|
    5@WM010$|
    5@WM010$|
    Here's the result for the same barcode when the application is run in JSE 6u10 (results for 6u23 are similar):
    5@WÞ10ä
    é@—M010$|
    5@W¥ð104|
    5°ùM0ó(▄♀
    5@W¥010$|
    é@WM010Ü\
    é@W¥010P\
    5@wy010$|
    5@m01Ð$▄
    )°W¥01è$|
    )@—0ÑÐ$|
    Well, at least it manages to get some characters right every time... ;-)
    The character values are wrong already when the KeyEvent for each is being created and posted to the EventQueue. But on the other hand, the problem is obviously tied to the JSE used, so it has to occur somewhere after Java receives the input and before a KeyEvent is generated. Since the errors are very random, we are guessing that it might be a timing problem.
    Between JSE 6u3 and 6u10, KeyEvent has received some new members (here with their typical values for my use case):
    #isSystemGenerated     true
    #primaryLevelUnicode     0     
    #rawCode     0     
    #scancode     0     
    Maybe the problem could have been introduced in the same changeset? Or maybe the values observed are meaningful in a way?
    Can anybody enlighten me, or give me a hint of any kind? I already scoured the bug database but did not find anything.
    Thanks! Any help is appreciated!
    Regards, Lars

    @mriem: Yes, I did. In all cases, it is "windows-1252". And moreover, if it were a problem with the default character set, it would not show the random behaviour it does.
    I also managed to create a reproducer that shows the behaviour:
    import static java.awt.event.KeyEvent.*;
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class ScannerTest {
         private static final String TEST = "5@WM010$|";
         private static final int DELAY = 50;
         private static final Map<Character, int[]> ALT_CODES = new HashMap<Character, int[]>();
         static {
              ALT_CODES.put('5', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD5, VK_NUMPAD3 });
              ALT_CODES.put('@', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD6, VK_NUMPAD4 });
              ALT_CODES.put('W', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD7, VK_NUMPAD7 });
              ALT_CODES.put('M', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD8, VK_NUMPAD7 });
              ALT_CODES.put('0', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD4, VK_NUMPAD8 });
              ALT_CODES.put('1', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD4, VK_NUMPAD9 });
              ALT_CODES.put('$', new int[] { VK_NUMPAD0, VK_NUMPAD0, VK_NUMPAD3, VK_NUMPAD6 });
              ALT_CODES.put('|', new int[] { VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD4 });
         public static void main(String[] args) throws Exception {
              System.out.println(java.nio.charset.Charset.defaultCharset().name());
              final int delay = DELAY;
              final JFrame frame = new JFrame("ScannerTest");
              SwingUtilities.invokeAndWait(new Runnable() {
                   @Override
                   public void run() {
                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        JScrollPane scrollPane = new JScrollPane(new JTextArea());
                        scrollPane.setPreferredSize(new Dimension(300, 600));
                        frame.add(scrollPane);
                        frame.pack();
                        frame.setVisible(true);
              new Thread() {
                   @Override
                   public void run() {
                        try {
                             Robot robot = new Robot();
                             for (int c = 0; c < 1000; c++) {
                                  if (frame.isActive()) {
                                       for (int i = 0; i < TEST.length(); i++) {
                                            int[] codes = ALT_CODES.get(TEST.charAt(i));
                                            if (frame.isActive()
                                                      && !(codes == null || codes.length == 0)) {
                                                 robot.keyPress(VK_ALT);
                                                 for (int code : codes) {
                                                      robot.keyPress(code);
                                                      robot.keyRelease(code);
                                                 robot.keyRelease(VK_ALT);
                                            robot.delay(delay);
                                       robot.keyPress(VK_ENTER);
                                       robot.keyRelease(VK_ENTER);
                                  } else {
                                       c--;
                                       try {
                                            Thread.sleep(delay);
                                       } catch (InterruptedException e) {
                                            e.printStackTrace();
                        } catch (AWTException e) {
                             e.printStackTrace();
              }.start();
    }

  • Getting key events without a jcomponent...

    Is it possible to get key events without adding a keylistener to a jpanel? I want a class of mine to manage input of it's own, but it has no reference to a jpanel. They don't necessarily have to be KeyEvents, but just some way to detect if a key has been pressed (like the arrow keys). How can I do this? Thanks.

    Lots of components can listen for key events.
    What does your class subclass?It doesn't subclass anything. I am creating a custom menu system for my game using images I have made for the tileset. I would like it to handle some keyboard events of its own. (Like if the down arrow is pressed, it will move the focus down to the next component on its own). Right now I am currently passing the key events from my fullscreen jpanel to the menu class and it is handling them that way. Thanks.

Maybe you are looking for