File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make the Java Default Button to trigger only on Enter Key Release

 
Hirantha Ranasinghe
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to Java Default button to work only on Enter Key Release event. Normally it works with Enter Pressed as well. I want to stop it.

Following is the code.



import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class ButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
buildFrame();
}
});
}

private static void buildFrame() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

JButton button = new JButton(new AbstractAction("Button") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ButtonTest::actionPerformed: CALLED");
}
});

JButton button2 = new JButton("Button 2");
InputMap im = button.getInputMap();
im.put(KeyStroke.getKeyStroke("ENTER"), "pressed");
im.put(KeyStroke.getKeyStroke("released ENTER"), "released");

f.setLayout(new GridBagLayout());
f.add(button);
f.add(button2);
f.getRootPane().setDefaultButton(button);

f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
 
Darryl Burke
Bartender
Posts: 5115
11
Java Netbeans IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hirantha, please BeForthrightWhenCrossPostingToOtherSites
http://stackoverflow.com/questions/12260962/how-to-set-the-java-default-button-to-react-on-enter-key-released

The advice you got on that thread is right on the money. If you didn't understand it enough to implement it, you could have asked for clarification instead of starting a new thread on another forum without telling us about the advice you already got.

Also, please learn to UseCodeTags.
 
Darryl Burke
Bartender
Posts: 5115
11
Java Netbeans IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Study the section of the Swing tutorial that deals with How to Use Key Bindings and you'll be able to do this yourself.

I would question the rationale behind this. What practical difference does it make whether the action is triggered by releasing, not pressing, the <Enter> key? What's different about your application that requires non-standard behavior?
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic