Search code examples
javaswingcompiler-errorsimageicon

Why does this code gives me the error "imageicon cannot be converted to int"?


I have a problem with adding a picture to my messagescreen. The code works if I don't use textfields in my box, but it also worked with the textfields and without the picture... I really don't get why I'm getting this error:

incompatible types: ImageIcon cannot be converted to int

This is my code:

import javax.swing.JOptionPane; 
import javax.swing.JTextField; 
import javax.swing.ImageIcon;

public class Input{    

    public static String[] geefInputNamen(){    
        JTextField veld1 = new JTextField(); 
        JTextField veld2 = new JTextField();

        Object[] velden = {  
            "Speler 1:", veld1,
            "Speler 2:", veld2
        };

        ImageIcon icon = new ImageIcon("nbalivemobile.png");

        JOptionPane.showConfirmDialog(null, velden, "Spelers vergelijken", 
                                   JOptionPane.OK_CANCEL_OPTION, icon);


        String[] namen = new String[2];

        namen[0] = veld1.getText(); 
        namen[1] = veld2.getText();

        return namen;
    }   
}

I'm new here, so I hope this is posted right. :)


Solution

  • If you want to pass an Icon to showConfirmDialog, you need to use the 6 argument overload:

    JOptionPane.showConfirmDialog(
        null,
        velden,
        "Spelers vergelijken",
        JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.PLAIN_MESSAGE, // Add this argument
        icon);
    

    I've used PLAIN_MESSAGE in this example, but you can use any one of ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE as specified in the API documentation.