我正在尝试使一个键在 JFrame 中发生某些事情。现在我只是想在你按下左键时禁用一个按钮,但没有任何反应。我以为我一切都正确,但它什么也没做。
编辑:我注意到当我不先点击开始时,它会起作用。但是按开始后,它不会响应。
到目前为止,这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener, KeyListener
{
private static final long serialVersionUID = 1L;
private JPanel p1;
private JButton b1, b2;
private JLabel lb1;
private int a;
private Font font = new Font("Arial", Font.BOLD, 20);
public MyFrame()
{
setLayout(new FlowLayout());
setSize(700,600);
setVisible(true);
setResizable(false);
addKeyListener(this);
setFocusable(true);
p1 = new JPanel(); add(p1);
p1.setBackground(Color.BLACK);
p1.setPreferredSize(new Dimension(650,500));
p1.setFocusable(true);
b1 = new JButton("Start"); add(b1);
b1.addActionListener(this);
b2 = new JButton("Test"); add(b2);
b2.setFocusable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
Graphics g = p1.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(30, 210, 10, 70);
g.fillRect(620, 210, 10, 70);
for(int i=0; i<7; i++)
{
g.fillRect(325, a, 10, 70);
a += 90;
}
g.setFont(font);
g.drawString("Player 1: ", 120, 20);
g.drawString("Player 2: ", 450, 20);
}
public void keyPressed(KeyEvent e)
{
int d = e.getKeyCode();
if(d==KeyEvent.VK_LEFT)
{
b2.setEnabled(false);
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
这是我的 Main.java 文件:
public class Main {
public static void main(String[] arg)
{
MyFrame mf = new MyFrame();
}
}
最佳答案
KeyListener
在焦点方面(以及其他方面)有很多问题。对于 Swing,最好使用 Key Bindings ,这让我们可以更好地控制焦点选项。 WHEN_FOCUSED
、WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
、WHEN_IN_FOCUSED_WINDOW
有不同的 InputMap
。他们的名字几乎是 self 记录的。所以如果我们要做
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
然后我们将获取框架聚焦时的 InputMap
。然后我们将 KeyStroke
与 Action
绑定(bind)到那个 InputMap
和组件的 ActionMap
。例如
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
imap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
ActionMap amap = panel.getActionMap();
Action leftAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
doSomethingWhenLeftIsPressed();
}
};
amap.put("leftAction", leftAction);
资源
关于java - 在 JFrame 中创建一个键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26625985/