-1

New to Java and can't seem to figure out the answer (even after searching everywhere). I want to add Submit, Clear, and Exit buttons to the program but can not seem to figure out how. I would like Submit to replace the current "ok" button, Exit to replace the current "cancel" button, and clear to clear all the inputted integers. Please see code below:

This is the main.

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;



class TestScoresApp {
    public static void main (String args[]) throws Exception {
        Scanner kb = new Scanner (System.in);

    while(true) {
    boolean flag = false;
    int array[] = new int[3];
    String strInput;
    System.out.println("Please Enter TestScores");



    for(int i=0;i<3;i++)
        //strInput = JOptionPane.showInputDialog(null, "Enter Score:");
        array[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter Number:"));
        //array[i]=kb.nextInt();
    try
    {
        TestScores t1 = new TestScores(array);
    }
    catch (InvalidTestScores e)
    {
        System.out.println(e.getMessage());
        flag = true;
}
if (flag == false )
    break;
else
    System.out.println("Invalid, input your scores again.");
}
        System.exit(0);
}
}

TestScores class

class TestScores {
    private int scores[] = new int[3];
    public TestScores (int test[]) throws InvalidTestScores {
        for (int i=0;i<3;i++) {
            if (test[i]<0 || test[i]>100)
                throw new InvalidTestScores (test[i]);
            else
                scores[i]=test[i];
        }

        System.out.println("Average is:"+Average());
    }
    public double Average() {
        double sum = 0;
        double avg;
        for(int i=0;i<3;i++) {
            sum += scores[i];
        }
        avg = sum / 3;
        return avg;
    }
}

Exception

class InvalidTestScores extends Exception {
    public InvalidTestScores (int n) {
        super("Error:Number cannot be less than 0 and greater than 100 i.e " +n);
    }
}
yangd01234
  • 241
  • 1
  • 3
  • 11

1 Answers1

1

To rename buttons, you should use another method of JOptionPane with arguments like this:

Object[] options = { "Submit", "Cancel" }; array[i] = = JOptionPane.showOptionDialog(null, "Enter number: ", "Title", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);

To add a new "Clear" button, use the following construct:

    final JButton clr= new JButton("Clear");
    clr.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
        // button implementation
        }
    });

Refer to this question for more info: ActionListener on JOptionPane

Community
  • 1
  • 1
Ivan Pronin
  • 1,768
  • 16
  • 14