Reputation:
I'm trying to make a key make something happen in a JFrame. Right now I'm just trying to disable a button when you press the left key, but nothing is happening. I thought I have everything right, but it does nothing.
EDIT: I noticed that when I don't click start first, it works. But after you press start, it won't respond.
Here's my code so far:
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)
{
}
}
And here's my Main.java file:
public class Main {
public static void main(String[] arg)
{
MyFrame mf = new MyFrame();
}
}
Upvotes: 1
Views: 136
Reputation: 208964
KeyListener
has a lot of problems, with regards to focus (among other things). With Swing, it is preferred to use Key Bindings, which gives us more control over the focus options. There are different InputMap
s for WHEN_FOCUSED
, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
, WHEN_IN_FOCUSED_WINDOW
. Their names are almost self documenting. So if we were to do
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
then we are getting the InputMap
for when the frame is focused. We would then bind a KeyStroke
with an Action
to that InputMap
and the component's ActionMap
. For example
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);
Resources
Upvotes: 3
Reputation: 344
You forgot to tell the JFrame that it should be listening for keys with this line of code:addKeyListener(this);
Upvotes: 1