Heres a sample code, i´ve tried most of the JButton settings but couldn´t figure it out.
import java.awt.event.*;
import javax.swing.*;
public class FailedMnemonic extends JFrame implements Runnable{
/*
*
* F4 to call button action
* ESC to dispose Dialog
*
* */
public FailedMnemonic() {
setSize(200, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
Panel p = new Panel(this);
p.setBounds(0, 0, 200, 60);
add(p);
};
public static void main(String args[]){
FailedMnemonic f = new FailedMnemonic();
f.setVisible(true);
}
@Override
public void run() {
}
public class Panel extends JPanel{
final JFrame f;
Action a = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
/*Here should be called the pressed animation from the button, dont know how
* maybe i should add the button as parameter on the dialog class so when is dispose the button returns to its original state*/
Dialog d = new Dialog(f, "...", true);
d.setSize(500, 200);
d.setVisible(true);
}
};
JButton b = new JButton();
public Panel(JFrame f){
this.f = f;
setLayout(null);
b.setBounds(0, 0, 150, 50);
b.setAction(a);
a.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_F4);
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), "meh");
getActionMap().put("meh", a);
b.setText("CLICK ME");
add(b);
}
public class Dialog extends JDialog{
public Dialog(JFrame OWNER, String title, boolean modal){
super(OWNER, title, modal);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addEscapeListener(this);
}
public void addEscapeListener(final JDialog dialog) {
ActionListener escListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}};
dialog.getRootPane().registerKeyboardAction(escListener,
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
}
}
}
Imports didn´t get into the block code
Don't call your classes "Frame" and "Dialog". There are AWT components with that name so it gets confusing. Use more description names (even if it is quick demo code).
Call JButton pressed animation using mnemonic
On Windows I get the animation when using Alt+F4, which is the mnemonic. I don't get the animation when I use F4, which is the Key Binding.
This makes sense because using Key Bindings
you just map a KeyStroke
to an Action
. It doesn't know the Action belongs to a button.
If you want to see the button animation then I would suggest you need to:
button.doClick()
.Note, you may also want to check out Escape Key and Dialog for a more complete Action. This Action will support closing of combo box drop downs using the escape key.