为什么applet上显示的文本在“keydown”或“keyup”事件中不会改变?

时间:2012-01-08 14:24:20

标签: java applet keydown japplet keyup

我想将显示的字符串从“start”更改为“keyup”或“keydown”,但字符串似乎没有改变..

import java.awt.Event;
import java.awt.Graphics;
import javax.swing.JApplet;

public class Applet extends JApplet {
    String str = "start..";
    public void init() {
    }
    public void paint(Graphics g) {
        g.drawString(str, 200, 200);
    }
    public boolean keyDown(Event evt , int key) {
        str = "keyDown";
        repaint();

        return true;
    }
    public boolean keyUp(Event evt , int key) {
        str = "keyUp";

        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

  1. 请勿使用 Java 1.1中弃用的方法。而是实现KeyListener或使用key bindings
  2. 确保小程序可以集中精力。有输入焦点。
  3. E.G。使用KeyListener

    KeyApplet

    // <applet code='KeyApplet' width=200 height=40></applet>
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.JApplet;
    
    public class KeyApplet extends JApplet implements KeyListener {
    
        String str = "start..";
    
        public void init() {
            setFocusable(true);
            requestFocusInWindow();
            addKeyListener(this);
            setBackground(Color.yellow);
        }
    
        public void paint(Graphics g) {
            super.paint(g);
            g.setColor(getBackground());
            g.fillRect(0,0,getWidth(),getHeight());
            g.setColor(Color.black);
            g.drawString(str, 20, 20);
        }
    
        public void keyTyped(KeyEvent evt) {}
    
        public void keyPressed(KeyEvent evt) {
            str = "keyDown";
            repaint();
        }
    
        public void keyReleased(KeyEvent evt) {
            str = "keyUp";
            repaint();
        }
    }