我认为您不想将焦点设置为JButton
(否则您将无法输入JTextArea
/JTextField
等),也许您希望它更改颜色并在输入某个字符时使其单击?
这是我做的一个例子:
当.被按下时,按钮背景将变为蓝色(并且按钮方法将调用SPACE在“。”之后自动插入):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Test {
final JFrame frame = new JFrame();
final JTextField jtf = new JTextField(15);
final JButton button = new JButton("SPACE");
public Test() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
insertSpace();
}
});
final Color defaultColor = button.getBackground();
jtf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, true), "period rel");
jtf.getActionMap().put("period rel", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
//button.doClick(); //I dont like this as it makes JBUtton look like its being clicked where as we want a color change
insertSpace();
button.setBackground(defaultColor);
}
});
jtf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0), "period pressed");
jtf.getActionMap().put("period pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
button.setBackground(Color.CYAN);
}
});
frame.add(jtf, BorderLayout.NORTH);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private void insertSpace() {
String s = jtf.getText();
jtf.setText(s + " ");
}
}