0

I am starting out with Java and I have a problem. When people click "a" on the java applet, I want it to draw a yellow rectangle and if they press anything else it draws a black rectangle but nothing happens.

    import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class guitarGame extends Applet implements ActionListener, KeyListener{

    Timer timer = new Timer (1000, this);
    String s = "";
    char a;
    int selection;

    public void keyReleased(KeyEvent ae){}

    public void keyPressed(KeyEvent ae){}

    public void keyTyped(KeyEvent ae){
        a = ae.getKeyChar();
    }

    public void init(){
        addKeyListener(this);
    }

    public void actionPerformed (ActionEvent ae)
    {
        if (a == a)
        {
            selection = 1;
        }
        else{
            selection = 2;
        }
    }

    public void paint (Graphics g)
    {
        if (selection == 1){
            g.setColor(Color.YELLOW);
            g.fillRect(100,100,100,100);
        }
        if (selection == 2){
            g.setColor(Color.YELLOW);
            g.fillRect(100,100,100,100);
        }
        repaint();
    }
}

Any help?

1
  • Should (a==a) be (a=='a')? Commented Apr 29, 2013 at 23:11

1 Answer 1

1

You are not doing anything with your KeyListener methods. Your ActionListener will never be called as it hasnt been registered with any component.

public void keyPressed(KeyEvent ae){
   char keyChar = ae.getKeyChar();
   if (keyChar == 'a' ) {
      selection = 1;
   } else {
      selection = 2;
   }

   repaint();
}

Some suggestions:

  • Don't call repaint inside paint - This will cause the latter to loop indefinitely
  • Use enums rather than magic numbers for paint selection.
  • Call super.paint(g)
  • Consider using Swing which has much better performance over the old heavyweight AWT.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I am starting out with Java -- thank you for the tips, the applet compiles and runs fine now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.