Search code examples
javauser-interfacejoptionpaneinputbox

InputDialog box showing a random "-1"


Everything runs perfectly but the String am1 = (String)JOptionPane.showInputDialog has a random default "-1" showing.

private void am1ActionPerformed(java.awt.event.ActionEvent evt) {     

getinfo();//Set the random question and answer
    am1.setEnabled(false);
Object[] options = {"Answer", "Cancel"};
int n = JOptionPane.showOptionDialog(null,
        JeopardyGUI.question1_1,//Reference the question set
        "",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.PLAIN_MESSAGE,
        null,     //do not use a custom Icon
        options,  //the titles of buttons
        options[0]); //default button title

    if(n == JOptionPane.YES_OPTION){
       String am1 = (String)JOptionPane.showInputDialog("",JOptionPane.PLAIN_MESSAGE);

       if(am1.equalsIgnoreCase(JeopardyGUI.answer1_1)){
           Jscore += 100;
           JOptionPane.showMessageDialog(null, JeopardyGUI.answer1_1 );
       }
       else if(!am1.equalsIgnoreCase(JeopardyGUI.answer1_1)){
           Jscore += -100;
           JOptionPane.showMessageDialog(null, JeopardyGUI.answer1_1 );
       }
 //           else
 //               am1.setEnabled(true);

    }
    if(n == JOptionPane.NO_OPTION){
        //am1.setVisible(false);
        am1.setEnabled(true);
    }
}                                   

Solution

  • You are using:

    public static String showInputDialog(Object message, Object initialSelectionValue)
    

    JOptionPane.PLAIN_MESSAGE is your initialSelectionValue in this case. It's an int which is equal to -1 I'm guessing. What you actually want is probably:

    JOptionPane.showInputDialog("Actual message", "");
    

    Also, be careful:

    String am1 = ...
    

    Is hiding am1 the class member which is some Component it seems.

    May I also suggest rewriting the handling logic as:

    if(am1 != null && am1.equalsIgnoreCase(JeopardyGUI.answer1_1)){
        Jscore += 100;
    else Jscore += -100;
    JOptionPane.showMessageDialog(null, JeopardyGUI.answer1_1 );