David
David

Reputation: 115

Cycle between operations on mouse clicked

I've encountered a problem on our homework in Java. We have to extend the class JPanel and then extend it in such a way, that if you click on the panel a dot appears, then another click connects the two dots, the third one closes a triangle and another click is a whole new cycle. That's where my problem lies. It's easy to write a code such that every click connects to the previous dot, but I am not sure how all this cycle is embedded in the code.

I am interested in some guidance and/or tips on what to use and how to proceed.

edit:

Turtle mariska = new Turtle();`

    protected void onMouseClicked(int x1, int x2, MouseEvent detail) {
        this.add(mariska);

        if (detail.isAltDown()) {
            mariska.setFillColor(Color.blue);
        } else {
            if (detail.isShiftDown()) {
                mariska.setFillColor(Color.green);
            } else {
                mariska.setFillColor(Color.red);
            }
        }

        mariska.moveTo(x1, x2);
        mariska.dot(5);     
    }
}

Upvotes: 0

Views: 113

Answers (1)

user1803551
user1803551

Reputation: 13427

I'd suggest using an enumeration to keep track of the click number and the corresponding operation, but I assume you haven't learned about it yet (if so and you want to see, leave a comment).

The following cycles between colors on mouse click and draws a square with that color:

public class Cycler extends JPanel {

    static int x;
    static int y;
    static int state = 0;

    Cycler() {

        setBackground(Color.WHITE);
        addMouseListener(new MyMouseListener());
    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        switch (state) {
            case 0:
                g.setColor(Color.RED);
                break;
            case 1:
                g.setColor(Color.BLUE);
                break;
            case 2:
                g.setColor(Color.GREEN);
                break;
        }
        g.fillRect(x, y, 20, 20);
    }

    class MyMouseListener extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {

            x = e.getX();
            y = e.getY();
            state = (state + 1) % 3;
            repaint();
        }
    }

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setContentPane(new Cycler());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

In your case, instead of changing the color, you would need to change the dawing operation (dot or line).

Upvotes: 1

Related Questions