我想将显示的字符串从“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;
}
}
答案 0 :(得分:1)
KeyListener
或使用key bindings。 KeyListener
// <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();
}
}