我正在尝试编写一个绘制圆圈的applet程序。如果按L键,圆圈的大小将增加,如果按S,则圆圈的大小将减小。
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class oval extends Applet implements KeyListener{
private int d=10;
@Override
public void init() {
setSize(500,500);
addKeyListener(this);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawOval(100, 100, d, d);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar()=='L')
d=d+5;
else if(e.getKeyChar()=='S')
d=d-5;
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
答案 0 :(得分:1)
if(e.getKeyChar() == 'l')
not
if(e.getKeyChar() == 'L') //this will work if the user presses Shift+l
我只是告诉你另一种方法,我设置的方式适用于小写l和大写l。所以它不区分大小写。
您没有正确使用KeyEvent来触发某个键。以下是您的代码测试和工作:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class oval extends Applet implements KeyListener
{
private int d=10;
@Override
public void init()
{
setSize(500,500);
addKeyListener(this);
}
@Override
public void paint(Graphics g)
{
super.paint(g);
g.drawOval(100, 100, d, d);
}
@Override
public void keyTyped(KeyEvent e)
{
}
@Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_L)
d=d+5;
else if(e.getKeyCode()==KeyEvent.VK_S)
d=d-5;
repaint();
}
@Override
public void keyReleased(KeyEvent e)
{
}
}
我删除了你通过keyReleased事件抛出的错误,因为我不知道为什么会这样...