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

Similar Messages

  • Handling KeyEvent in a JFrame

    i have a JFrame with several JTextFields. i want the JFrame to register the enter key whent it is pressed in any of those textFields. basically, i want the JFrame to react to "enter" keyEvent as if the "ok" button is pressed.
    how do i do that?

    You don't need the additional overhead of a key listener just for the <enter> key
    myTextField.addActionListener(this)

  • Bridge meta data handling and filtering

    It would be great if you could add two features:
    1.  adding keywords to multiple files currently if two files share the same  keywords but not in the order, adding new is impossible without  overwriting the existing keywords
    2. filtering by location data, it would be great to filter by country say, just as by keyword, date or other.
    Thanks, Erik

    For adding keywords without removing existing keywords, this script might be of use to you...
    http://www.ps-scripts.com/bb/viewtopic.php?f=19&t=2364&sid=57a50afd1b53b5fc195f0e5dfdbfab0 6

  • OBIEE web services: Handling saved filters

    I was trying to call obiee web services to get report data. And I used ReportParams to pass the prompt values. But this was not working in case of saved filters in the report.
    Plz advice .....

    searching.gif is referred through CSS files, thus replace the searching.gif (under res\sk_oracle10\b_mozilla_4) with another custom created blank gif and name it as searching.gif....rename the original searching.gif to searching_original.gif for reference.
    caveat: This will affect your enterprise wide display.
    mark answers promptly.
    J
    -bifacts
    http://www.obinotes.com

  • JTextArea doesn't show expected reaction on filtered KeyEvents

    In my app I've implemented a custom KeyEventDispatcher to process all incoming key events and translate the carried KeyChars into new ones. A JTextArea behaves as expected (showing translated characters during typing), the only exception are the german umlauts, the '�' and shift+circumflex (german keyboard on X). These characters appearing not translated, although the desired replacement of the key char is done in the dispatcher.
    If an other focus enabled component (e.g. a JPanel) is focussed, all incoming (and expected) key-typed events arrive, with the JTextArea not all typed keys appearing as key-typed, the exceptions mentioned before are just only key-released events.
    Any hints?

    I'm not sure if this will help you, because you are using a different mechanism to translate the key event.
    You can extend javax.swing.text.PlainDocument and implement
    class MyDocument extends PlainDocument {
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    // Translate str by replacing with the characters you like and then call super.insertString
    // For exapmle str = str.toUpperCase() will type only upper case characters into the text area
    super.insertString(offs, str, a);
    Then implement createDefaultModel in JTextArea to create your own document.
    protected Document createDefaultModel() {
    return new MyDocument();
    }

  • Handle request.setCharacterEncoding among multiple filters

    Hi,
    My application handles multiple filters and these filters called alternatively based on url-pattern. But I want to make sure request.setCharacterEncoding was set start of each filter.
    How can I do this?? I dont want to use head filter because that will increase my filters count.
    I would appriciate if you suggest me some ideas on it.

    Is that any way i can get set done on web.xml??

  • Handling event from background ?

    I like to listen and handle KeyEvent which is occured
    during my application is in background or deiconized.
    Is it possible ? How can I do that?
    Please...give me some advice !

    KeyEvents will only be processed by your app when it's in the foreground. If you need to capture keyEvents everywhere, you would need to use JNI and write c/c++ code implementing a KeyHook

  • Improve The Current Implementation Of A Simple JQuery Filtering Engine

    The filtering option on my site appears to be behaving erratically, and not returning the closest result (i.e. items that best match the set filters), but rather "generalising" across the board. I think that this is down to the manner in which
    I have implemented the if-else statement that handles the filtering. I think that it would work well if there was just one option, but now that there are multiple, any options selected later would simply be overridden by earlier ones.
    What would be the best way to improve the current implementation of my filtering engine, so that it would make matches more effectively?
    $('body').on('click', '#reset-button', function (event) {
    $('.rideshare-item').show();
    $('body').on('click', '#search-button', function (event) {
    // Collect values
    var date = $('.date').val().trim();
    var time = $('.time').val();
    var seatsAvailable = $('.seats-available').val();
    var womenOnly = $("input[name='women-only']:checked").length ? "Yes" : "No";
    var luggageSpace = $("input[name='luggage-space']:checked").length ? "Yes" : "No";
    $('.rideshare-item, .no-result').hide();
    $('.rideshare-item').each(function (a, b) {
    var rideshareDate = $(b).data('date');
    var rideshareTime = $(b).data('time');
    var rideshareSeats = $(b).data('seats');
    var rideshareWomen = $(b).data('women');
    var rideshareLuggage = $(b).data('luggage');
    if (date.length == 0) {
    $(this).closest('.rideshare-item').show();
    } else if (date.length > 0) {
    var timestamp = Date.parse(date)
    if (isNaN(timestamp) == false) {
    if (parseDateEntry(date).getTime() == parseDateAttribute(rideshareDate).getTime()) {
    $(this).closest('.rideshare-item').show();
    // additional if-else statements can be found on the jsfiddle
    if (rideshareSeats > seatsAvailable) {
    $(this).closest('.rideshare-item').show();
    if (womenOnly == rideshareWomen) {
    $(this).closest('.rideshare-item').show();
    if (luggageSpace == rideshareLuggage) {
    $(this).closest('.rideshare-item').show();
    The jsfiddle here contains a working example:
    http://jsfiddle.net/gpk1f11o/

    and...

  • Filtering JTable

    Assume you have an app that has a JTable displayed on the main frame. There is also a combo box that goes with this JTable for use in filtering the JTable so that only the desired entries are shown in the table.
    What is the proper way to handle this filtering?
    Do I need to work with the original table model? Or should I create a new table model for each filter action and then find a way to replace the table model that the JTable is using?

    I created a tablemodel which accepts an arraylist of objects which are essentially the rows. When I want to filter, I replace that arraylist with a new list (setList() method in tablemodel) which has the filtered records. When a filter is changed, make a new call to the database to get the rows. Or you might want to add a isInSet() method to the row object to simplify building a filtered list from a 'full list'. The outer container (which contains the table and combo) controls which list is displayed.
    My code is not very relevant because I built custom SQL statements based on criteria entered in a table and most of the work is done by a custom record cache class I wrote. This means the logic I described above is scattered through several classes.

  • EventHandler T T doesn't recognize KeyEvent, bug?

    "type argument KeyEvent is not within bounds of Type-Variable T
    where T is a Type-Variable
    T extends Event declared in the interface EventHandler
    {code}
    http://docs.oracle.com/javafx/2/events/handlers.htm  this code doesn't work
    {code}
    Example 4-3 Handler for the Key Nodes
    private void installEventHandler(final Node keyNode) {
        // handler for enter key press / release events, other keys are
        // handled by the parent (keyboard) node handler
        final EventHandler<KeyEvent> keyEventHandler =
            new EventHandler<KeyEvent>() {
                public void handle(final KeyEvent keyEvent) {
                    if (keyEvent.getCode() == KeyCode.ENTER) {
                        setPressed(keyEvent.getEventType()
                            == KeyEvent.KEY_PRESSED);
                        keyEvent.consume();
        keyNode.setOnKeyPressed(keyEventHandler);
        keyNode.setOnKeyReleased(keyEventHandler);
    {code}
    nor does this code, which I copied from a eventHandler<MouseEvent>
    {code}
    class keyHandler implements EventHandler<KeyEvent>
    private final Node node;
        keyHandler(Node node)
           this.node= node ;
        @Override
        public void handle(KeyEvent event)
    {code}
    I'm going to make a jira report once I get confirmation from someone here, even though it's pretty obvious since the Tutorial example produced the same error.
    I am using Netbeans Lambda 8, with JDK 8 build-84
    InputEvent doesn't work either, going to try some others...  so far MouseEvent and DragEvent are the only working ones.
    Edited by: KonradZuse on Apr 13, 2013 10:44 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Wow :p.... I completely forgot about the duplicate set of imports.... I always do control + alt + i to import everything, so sometimes AWT stuff pops in there when it shouldn't, suprirsed I didn't think of that myself, but 2 am coding does that to you :p.
    Thanks a ton, I really appreciate it, i had no idea what was going on hahaha...
    I think it's weird that MouseEvent and DragEvent are set to FX import first... Is there a settign in netbeans that I can force the importer to use FX > all? Most of the time it's good, but as you see in this case sometimes AWT likes to bother me :P
    Edited by: KonradZuse on Apr 14, 2013 11:02 AM

  • Java FX, TextField, Keyboard handling

    I need to look for specific characters that may be typed in a text field and perform an action accordingly. For example if the user hits F1 key while inside a textfield, i need to popup a different panel. I am using FXML to do the form layout. Please help mw with some example code. If I can set these functions at a global level (Scene) it would be even better way, for example no matter which ever text field use is on, I need to handle F1 key the same way.
    Thank you

    What am I doing wrong?F1 key presses don't generate KeyTyped events, you need to handle KeyPressed events to receive the function key presses, so perhaps use onKeyPressed="#handleKeyInput" in your FXML instead.
    I haven't used FXML, so perhaps there are other issues in the way you have defined the interaction between the FXML and the controller code, but I don't really know.
    The code below will globally catch any F1 key presses for any TextFields in the scene, so maybe you could just install the keyfilter when you setup your scene rather than placing a reference to an onKeyPressed handler for each TextField in your FXML.
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.input.*;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    public class TextFieldTrapper extends Application {
      public static void main(String[] args) { Application.launch(args); }
      @Override public void start(Stage primaryStage) {
        // create some controls.
        final Label eventText = new Label("Press F1 in any text field to capture a KeyEvent");
        TextField text1 = new TextField("Some Text"); text1.setId("text1");
        TextField text2 = new TextField("More Text"); text2.setId("text2");
        // layout the scene.
        final VBox root = new VBox(5);
        root.setStyle("-fx-background-color: cornsilk; -fx-padding: 10;");
        root.getChildren().addAll(text1, text2, eventText);
        primaryStage.setScene(new Scene(root, 1000, 100));
        // monitor and respond to any F1 key presses sent to any text field in the scene.
        root.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
          @Override public void handle(KeyEvent event) {
            if (KeyCode.F1.equals(event.getCode()) && event.getTarget() instanceof TextField) {
              eventText.setText(event.toString());
        primaryStage.show();
    }

  • Aironet 600 with Mac Filtering and a switch..

    How does the Aironet 600 handle Mac Filtering if I were to connect a switch to port 4 on the back ("Secured" network port). Does it authenticate each MAC or does it do somthing similar to how 802.1x with multi-host works, the first mac authenticates and then the port's wide open? My use-case here is a printer at a remote home-office. The printer doesn't have a supplicant in it so I need to use mac filtering. Thanks.

    MAC authentication is all I use for my OutStationed workers.  No wifi, just the rlan.  Since the rlan is configured for DHCP only, no IP gets passed until MAC auth occurs.
    When Cisco packaged this up, they said 4 is enough..  IF you use an un-managed (non-cisco) switch. 
    I had a need for 2 workstations and 2 digiports..  SOP sys a managed switch..  oops.  the switch consumed 2 MAC's right off the top.. 1 for itself and 1 for each vlan.
    After enablilng 2 rlans, and configuring a pair on different networks, we discovered that they were bridged in the 602 (or somewhere).
    We ended up switching out the 602 for an ASA5505

  • KeyEvent key code problem

    This is about JavaFX 2.0.
    For the code fragment:
    flow.setOnKeyPressed(new EventHandler<KeyEvent>() {
                public void handle(KeyEvent keyEvent) {
                          .....When the SLASH key is pressed, breaking at the first line of the method "handle" gives keyEvent.getCode().ordinal() being 187. When the MINUS key is pressed, keyEvent.getCode().ordinal() is STILL 187. Previously in JavaFX 1.3, the code ordinal was 23 for SLASH and 21 for MINUS. Now I cannot tell which key is pressed! Yes I can look at the keyEvent.getText() property... but it really seems like a bug that the code is UNDEFINED, right?
    Thanks everyone :)
    Edited by: 851528 on Jun 3, 2011 12:10 AM

    I'm not so sure that RT-13972 is the same bug as what is being discussed here. I would encourage you to file a separate bug in http://javafx-jira.kenai.com against Runtime/Glass.
    Thanks
    Jonathan

  • DPS6.3 modify default connection handler?

    While making some changes in a dps through the dscc I edited the default connection handler and added two connection policies. I have now lost access to the dps through the dscc possibly because of the policies added.How do I fix the default connection handler? Is there a dpconf command to read it, and delete the policies?
    Edited by: Xoth on Jun 11, 2009 12:38 PM
    FIXED. I figured it out. Looking at reference manual instead of admin where the dpconf commands are.
    dpconf get-connection-handler-prop -h host -p port "default connection handler"
    dpconf set-connection-handler-prop -h host -p port "default connection handler" request-filtering-policy:no-filtering
    dpconf set-connection-handler-prop -h host -p port "default connection handler" resource-limits-policy:no-limits

    Dummy post to increase the reply count. Sorry for the noise.

  • Filters not responding...

    None of my filters are responding. I have rebooted several times with no luck;
    any thoughts?
    Thanks,
    Carlos

    Me and andynick will be really interested to know if trashing the prefs accomplishes this miracle.
    I don't want to imply anything here but, umm, a couple of recent posts we have handled on "filters don't work" have been simple operator error; applying a filter to a clip in the Browser and not in the timeline. Can't tell from the post if this is possible or if it's just t-o-o obvious.
    bogiesan

Maybe you are looking for

  • MSI X48C Platinum and DDR3 corsair 2x4 GB @ 1600mhz WILL IT WORK??

    Hi , I truly appreciate the mere existence of this forum . my system is : PSU : Corsair 650HX CPU : Intel Core2Duo E6750 GPU : Geforce GTX 260 RAM : (currently 2x1gig DDR2 @ 667 Mhz) and i just bought 2x4gb dims of DDR3 ram (corsair vengeance) it doe

  • How do i edit photos?

    hi all, new ipod nano-2 gb owner here. can somebody tell me how to edit my photos. i want to delete and or add a photo or two. i would like to keep my i-photo file intact. i don't want to have to try and remember which photos were in it. i would also

  • Order by problem

    hi all i have to make a report that has group fields. and i need to change order by of this query in runtime query must be ordered by each field that user select in runtime. if i use sql query for making this report and at the end of my sql statement

  • Planning objects

    Hi Friends, In which table  i can  found all planning objects(like cubes,dso,Infoobjects)? Thanks in advance, Sateesh.

  • Db13 back up error BR0278E, BR0279E, BR0222E

    Dear basis gurus, I am attaching the error details, What may be the cause? Detail log:                    bdvzqlev.afd BR0051I BRBACKUP 7.00 (24) BR0055I Start of database backup: bdvzqlev.afd 2007-08-24 21.00.01 BR0484I BRBACKUP log file: E:\oracle\