我有一个放在JPanel中的JButton。现在我已经通过AbstractAction为这个按钮添加了一个关键的监听器。但我想要的是:说我已经分配了键盘键' A'到这个按钮。现在当我按下键A' A'我想表明在GUI上按下按钮。我尝试使用Jbutton.setEnabled()。但是这不起作用,因为我必须启用&取消按钮。我想AbstractAction中的动作最后会被执行而不是在中间。我在下面发布了我的代码:
private Action buttonPressed(final JButton jButton,final Boolean black) {
// TODO Auto-generated method stub
AbstractAction buttonPressed = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int index=keys_names.indexOf(e.getActionCommand().toUpperCase());
if(index>=0)
{
jButton.setEnabled(false);
// DO some other action
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
jButton.setEnabled(true);
}
}
};
return buttonPressed;
}
和使用的JButton是:
JButton b1=new JButton();
b1.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A,0), keys_names.get(key_press));
b1.getActionMap().put(keys_names.get(key_press),buttonPressed(b1,false));
答案 0 :(得分:0)
你可以简单地调用JButton#doClick
,它可以模仿按下按钮,直观地调用按钮ActionListener
。但是你想要真正强调这一事实,你可以使用JButton#doClick(int)
,这将允许你传递按钮应该“按下”的时间
例如......
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestButton {
public static void main(String[] args) {
new TestButton();
}
public TestButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton b1 = new JButton("Click Me");
b1.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "bang");
b1.getActionMap().put("bang", new ClickMeAction());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(b1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ClickMeAction extends AbstractAction {
public ClickMeAction() {
putValue(NAME, "Click me");
}
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
btn.doClick(1000);
}
}
}