john_angevin
john_angevin

Reputation: 47

Java, JoptionPane: the yes-no dialog keeps on showing

I'm trying to solve an exercise from a Java textbook, that requires to write a piece of code that opens a yes-no gialog which asks the user if he wants to draw and color a solid circle in red (yes) or not (no), in which case the color is black (by default; but for clarity I decided to include in my piece of code a specific statement anyway). I thought of (IDE: NetBeans) ...:

int centre = JOptionPane.showConfirmDialog(null, "Do you want I turn the solid center circle color from black to red?", 
                    "Click Yes or No:", JOptionPane.YES_NO_OPTION);

            if (centre == JOptionPane.YES_OPTION)
            {
                canvas.setColor(Color.RED);

            }
            else if (centre == JOptionPane.NO_OPTION)
            {
                canvas.setColor(Color.BLACK);
            }

            canvas.drawOval(200, 200, 100, 100);
            canvas.fillOval(225, 225, 50, 50); 

..., but the dialog keeps on opening again and again after choosing either choice. Without the dialog + else-if branching the code executes correctly, even though by drawing the solid circle only in red or black according you include the canvas.setColor(Color.RED); statement or not. What [do I miss/don't I know] ? Many thanks to all those who'll be able to suggest me the simplest (hey! I'm a beginner) way to write the required piece of code. And many thanks to all the others too :) .

Upvotes: 0

Views: 209

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

You probably have this code inside paintComponent(), which is a very, very bad idea. paintComponent() is called every time swing needs to paint the component.

This dialog box should be called in an event listener instead (i.e. when the user clicks a button, for example). It should then store the answer in some boolean field, and the paintComponent() method should read that boolean field to decide what to draw.

Upvotes: 3

Related Questions