键盘画直线疑问
为什么不能画直线import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawLine extends JFrame implements KeyListener
{
int x=getWidth()/2;
int y=getHeight()/2;
int firstx=getWidth()/2;
int firsty=getHeight()/2;
private Graphics g;
public DrawLine()
{
setFocusable(true);
addKeyListener(this);
}
public static void main(String args[])
{
DrawLine frame=new DrawLine();
frame.setTitle("DrawLine");
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
/*frame.x=frame.getWidth()/2;
frame.y=frame.getHeight()/2;
frame.firstx=frame.getWidth()/2;
frame.firsty=frame.getHeight()/2; */
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped (KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
g=getGraphics();
switch(e.getKeyCode())
{
case KeyEvent.VK_DOWN:y+=10;break;
case KeyEvent.VK_UP:y-=10;break;
case KeyEvent.VK_LEFT:x-=10;break;
case KeyEvent.VK_RIGHT:x+=10;break;
}
g.drawLine(firstx,firsty,x,y);
firstx=x;
firsty=y;
}
}
把int x=getWidth()/2;
int y=getHeight()/2;
int firstx=getWidth()/2;
int firsty=getHeight()/2;
删去,把注释符号删去,使frame.x=frame.getWidth()/2;
frame.y=frame.getHeight()/2;
frame.firstx=frame.getWidth()/2;
frame.firsty=frame.getHeight()/2;能执行
为什么能画直线
KeyPressed方法怎么能调用frame的x ,y, firstx,firsty