how to make the key arrows work?
I am using Java and I can't make the key arrows work in the applet , can anyone help me? Here's the code I wrote
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JApplet;
import javax.swing.JLabel;
public class KeyboardJApplet extends JApplet {
int weigh = 20;
int height = 20;
JLabel c;
@Override
public void init() {
while (true) {
try {
setFocusable(true);
c.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ke) {
int e = ke.getKeyCode();
/*
switch (e) {
case KeyEvent.VK_RIGHT:
weigh++;
break;
case KeyEvent.VK_LEFT:
weigh--;
break;
case KeyEvent.VK_UP:
height++;
break;
case KeyEvent.VK_DOWN:
height--;
break;
}
*/
if (e == KeyEvent.VK_RIGHT) {
//c.setLocation(c.getX()+1,c.getY());
weigh++;
repaint();
}
if (e == KeyEvent.VK_LEFT) {
//c.开发者_StackOverflow中文版setLocation(c.getX()-1,c.getY());
weigh--;
repaint();
}
if (e == KeyEvent.VK_UP) {
//c.setLocation(c.getX(),c.getY()-1);
height--;
repaint();
}
if (e == KeyEvent.VK_DOWN) {
//c.setLocation(c.getX(),c.getY()+1);
height++;
repaint();
}
}
});
add(c);
} catch (NullPointerException e) {
}
}
}
@Override
public void paint(Graphics g) {
JLabel c = new JLabel("java");
g.drawString(c.getText(), weigh, height);
}
}
You should not have a while (true) loop in the init method.
Custom painting is done by overriding the paintComponent() method of a JPanel (or JCompnent) and then you add the component to the applets content pane. Read the section from the Swing tutorial on Custom Painting for more inforamtion and examples.
If you want to respond to key presses then you should use Key Bindings, not a KeyListener.
You don't need to create a label and then use getText() to get the text to paint.
I suggest you take time to read the Swing tutorial for the basics.
精彩评论