Search code examples
javaif-statementjtextfield

How do I printout multiple text in JText Field using if/else statement?


    private void resultActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    if(pick1 > pick2 ){
    resultstf.setText("The New President is Koon!");
    }
    else if(pick2 > pick1){
    resultstf.setText("The New President is Baam!");
    }
    else if(pick1 == pick2){
    resultstf.setText("The Result for the new President is a Tie! Please Vote Again.");
    }
    if(pick3 > pick4){
    resultstf.setText("The New VP is Sachi!");
    }
    else if(pick4 > pick3){
    resultstf.setText("The New VP is Faker!");
    }
}

How do I print out multiple Text whenever I press the Result Button? Like I want to print out "The New President is Koon" and also printout "The New VP is Sachi" at the same time.


Solution

  • Use a StringBuilder and build the message as you go along:

    private void resultActionPerformed(java.awt.event.ActionEvent evt) {
        StringBuilder message = new StringBuilder();                                   
        // TODO add your handling code here:
        if (pick1 > pick2) {
            message.append("The New President is Koon!\n");
        }
        else if (pick2 > pick1) {
            message.append("The New President is Baam!\n");
        }
        else if (pick1 == pick2) {
            message.append("The Result for the new President is a Tie! Please Vote Again.\n");
        }
        if (pick3 > pick4) {
            message.append("The New VP is Sachi!\n");
        }
        else if (pick4 > pick3) {
            message.append("The New VP is Faker!\n");
        }
    
        resultstf.setText(message.toString());
    }