samedi 1 octobre 2016

Repeating controlChanges on GUI

I'm working on learning about using events to change things on the GUI. I am currently using Controller Events passed from another method and I think I may be missing some key information about how variables work in these methods. Here is my source code (this is currently an inner class).

class MyDrawPanel extends JPanel implements ControllerEventListener{

    static boolean isWriting = false;

    public void controlChange(ShortMessage event) {
        isWriting = true;
        repaint();
    }

    public void paintComponent(Graphics g){

        if (isWriting){
            int red = (int) (Math.random() * 250);
            int green = (int) (Math.random() * 250);
            int blue = (int) (Math.random() * 250);

            g.setColor(new Color(red, green, blue));

            int xpos = (int) (Math.random() * 190 + 10);
            int ypos = (int) (Math.random() * 190 + 10);
            int width = (int) (Math.random() * 50 + 10);
            int height = (int) (Math.random() * 50 + 10);
            g.fillRect(xpos, ypos, width, height);


            //isWriting = false;
        }

What I'm trying to do is draw a new rectangle every time the listener receives an event but I can only get one of two things to happen. If I try to set "isWriting" back to false at the end of the if statement the if statement seems to continuously evaluate to false and not draw any rectangles. If I comment out that code to set isWriting back to false the drawing works for a single rectangle but there is nothing to change the variable back and call the repaint method so I only get a single rectangle.

I know that my events are getting to the listener as I've used a sout to increment a count every time it gets an event so it seems the problem is with the state of the isWriting variable. Thanks for the help!

Aucun commentaire:

Enregistrer un commentaire