Java的新手,似乎无法找到答案(即使在搜索到处之后)。我想在程序中添加“提交”,“清除”和“退出”按钮,但似乎无法弄清楚如何。我想提交以替换当前的“确定”按钮,退出以替换当前的“取消”按钮,并清除以清除所有输入的整数。请参阅以下代码:
这是主要的。
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 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;
}
}
异常
class InvalidTestScores extends Exception {
public InvalidTestScores (int n) {
super("Error:Number cannot be less than 0 and greater than 100 i.e " +n);
}
}
答案 0 :(得分:1)
要重命名按钮,您应该使用JOptionPane
的另一种方法,其参数如下:
Object[] options = { "Submit", "Cancel" };
array[i] = = JOptionPane.showOptionDialog(null, "Enter number: ", "Title",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
要添加新的“清除”按钮,请使用以下构造:
final JButton clr= new JButton("Clear");
clr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// button implementation
}
});
有关详细信息,请参阅此问题:ActionListener on JOptionPane