如何从 if 语句运行 Java Applet?

How to run the Java Applet form an if statement?

在我的代码中,我想让方法 paintComponent1(画一条线)根据按键是否被按下来运行。我该怎么做?感谢所有帮助,谢谢:D!

这是我的代码:

    import java.awt.event.KeyEvent;
    import java.awt.*;
    import java.applet.Applet; 


    public class Test {
    boolean x = false;

    public void paintComponent1(Graphics g){
       g.drawLine(35, 60, 100, 120);


    }


    public void keyPressed(KeyEvent e) {
      x = true;
    }

    public void keyReleased(KeyEvent e) {
      x = false;
    }


    public void paintComponent(Graphics g) {
      if (x) 
          paintComponent1();

}
}

为什么不直接将 paintComponent1() 移动到 keyPressed 方法中?

public void keyPressed(KeyEvent e)
{
    if(e.getKeyCode() == KeyEvent.VK_SPACE) // if you press the space bar key
    {
        paintComponent1();
    }
}