0

In my code, I would like to have the method, paintComponent1 (draw a line) to run based on whether or not the key is pressed. How would I go about that? All help is appreciated, Thanks :D!

Here is my code:

    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();

}
}
HLatfullin
  • 13
  • 2
  • 8
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Jan 04 '15 at 03:41

1 Answers1

0

Why don't you just move paintComponent1() into the keyPressed method?

public void keyPressed(KeyEvent e)
{
    if(e.getKeyCode() == KeyEvent.VK_SPACE) // if you press the space bar key
    {
        paintComponent1();
    }
}
ProgrammingIsAwsome
  • 1,109
  • 7
  • 15
  • It says that it is not applicable for arguments. What do I do about that? – HLatfullin Jan 02 '15 at 18:22
  • Howw you mean not applicable for arguments? Did my solution not work? – ProgrammingIsAwsome Jan 02 '15 at 18:29
  • It just gives an error and says that "The Method paintComponent1(Graphics) in the type Test is not applicable for the arguments ()" – HLatfullin Jan 02 '15 at 18:42
  • Then you have to give it an argument. Your methode signature is paintComponent1(Graphics g), so you have to pass an argument of type Graphics. But the logic of my solution is this, that the actions you want to take if an event happens, you have to put in the specific method. – ProgrammingIsAwsome Jan 02 '15 at 18:47