下面是一个示例代码,我尝试了大部分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);
}
}
}
}
进口没有进入区块代码
答案 0 :(得分:2)
不要将您的课程称为“框架”和“对话框”。有名称的AWT组件让它变得混乱。使用更多描述名称(即使它是快速演示代码)。
使用助记符
调用JButton按动画
在Windows上,我使用Alt + F4获取动画,这是助记符。当我使用F4时,我没有得到动画,这是Key Binding。
这是有道理的,因为使用Key Bindings
您只需将KeyStroke
映射到Action
。它不知道Action属于一个按钮。
如果你想看按钮动画,那么我建议你需要:
button.doClick()
。注意,您可能还需要查看Escape Key and Dialog以获取更完整的操作。此操作将支持使用转义键关闭组合框下拉列表。