0

I'm trying to make a message dialog appear when the user enters an invalid input.

When I try to use null as the location for the dialog, the dialog appears correctly when 0 or a negative number is entered, but there's no title or text in the dialog.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // draw lines

    endY = getHeight(); // bottom
    endX = getWidth(); // right side
    Input = Integer.parseInt(inputField.getText());

    if (Input > 0 ) {

        for (int beginY = getHeight() / 2; beginY <= endY; beginY += Input) {
            g.drawLine(0, beginY, endX, beginY);
        }

    } else {
        JOptionPane.showMessageDialog(null, "Please do not enter 0 or a negative number.", "Wrong input", JOptionPane.ERROR_MESSAGE);
    }
}

I've tried using my JFrame object which has been declared and initialized in a different class as the first parameter and this works.

However, I want to be able to use this code in my JPanel class in the paintComponent method so I can add if/else logic to it when drawing the lines.

ali_m
  • 71,714
  • 23
  • 223
  • 298
Bytecode
  • 47
  • 6

1 Answers1

0

The paintComponent method is called whenever something in the AWT EDT (Abstract Window Toolkit Event Dispatching Thread) thinks the component needs to be repainted. That method is called often and often at moments you didn't expect it to be called. So, don't show a JOptionPane in the body of that method. You have to take that logic out of the method and show it when needed.

You could do something like this, but this is not a good programming practice:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (canPaint) {
        // Do some painting if we can
        // Lets say an error occurred:
        // If the dialog is shown over the component then the component will
        // be redrawn. Now, we don't want this code to loop, so we set a
        // flag to control the "loop".
        canPaint = false;

        // Now we tell the AWT event queue that we want to show the message
        // whenever it get's a chance, because the Dialog won't be drawn
        // properly if it's called here.
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                showWarning();
            }
        });
    }
}

void showWarning() {
    javax.swing.JOptionPane.showMessageDialog(null, "Syntax Error : ", "Incorrect user input", javax.swing.JOptionPane.ERROR_MESSAGE);
}

But in general never do programming logic inside the paintComponent method!

For more information see this post: http://www.java-forums.org/new-java/26110-joptionpane-when-called-inside-paintcomponent-method.html

nbro
  • 15,395
  • 32
  • 113
  • 196