这是一个示例代码,我尝试了大多数 JButton 设置,但无法弄清楚。
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);
}
}
}
}
导入没有进入块代码