如何使关键箭头起作用?

问题描述

| 我正在使用Java,但无法使小箭头在applet中起作用,有人可以帮助我吗?这是我写的代码
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.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);
    }
}
    

解决方法

        init方法中不应有while(true)循环。 通过重写JPanel(或JCompnent)的paintComponent()方法来完成自定义绘制,然后将组件添加到applet内容窗格。阅读Swing教程上有关自定义绘画的部分,以获取更多信息和示例。 如果要响应按键,则应使用按键绑定,而不是KeyListener。 您无需创建标签,然后使用getText()即可绘制文本。 我建议您花些时间阅读Swing教程的基础知识。