我正在用Java創建一個簡單的GPA計算器。它使用JOptionPane,但我希望用戶能夠在一個窗口中回答所有問題。所以,我正在試驗JPanel。難以使JButton工作
當用戶點擊「提交」按鈕時,我希望程序計算出GPA。我無法確定如何合併事件處理程序。
下面是代碼:
import java.math.RoundingMode;
import java.text.DecimalFormat; format.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
public class MyGpaCalc extends JFrame {
public static void createGuiWindow() {
JFrame frame = new JFrame("GPA Calculator");
frame.setSize(300,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel aGradesLabel = new JLabel("# credits earned with A grade: ");
JTextField aGradesText = new JTextField(3);
JLabel bGradesLabel = new JLabel("# credits earned with B grade: ");
JTextField bGradesText = new JTextField(3);
JLabel cGradesLabel = new JLabel("# credits earned with C grade: ");
JTextField cGradesText = new JTextField(3);
JLabel dGradesLabel = new JLabel("# credits earned with D grade: ");
JTextField dGradesText = new JTextField(3);
JLabel fGradesLabel = new JLabel("# credits earned with F grade: ");
JTextField fGradesText = new JTextField(3);
JButton submit = new JButton("Submit");
panel.add(aGradesLabel);
panel.add(aGradesText);
panel.add(bGradesLabel);
panel.add(bGradesText);
panel.add(cGradesLabel);
panel.add(cGradesText);
panel.add(dGradesLabel);
panel.add(dGradesText);
panel.add(fGradesLabel);
panel.add(fGradesText);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
createGuiWindow();
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.FLOOR);
double aGrades = Double.parseDouble(aGradesText.getText());
double bGrades = Double.parseDouble(bGradesText.getText());
double cGrades = Double.parseDouble(cGradesText.getText());
double dGrades = Double.parseDouble(dGradesText.getText());
double fGrades = Double.parseDouble(fGradesText.getText());
double totalCredits = aGrades + bGrades + cGrades + dGrades + fGrades;
double gradePoints = (aGrades * 4) + (bGrades * 3) + (cGrades * 2) + (dGrades * 1) + (fGrades * 0);
double sum = gradePoints/totalCredits;
System.exit(0);
}
}
謝謝。如果有人知道更多關於我的特定代碼的建議,那麼理解教程就容易多了。當我有機會再次處理這個問題時,我會公佈結果! – JennyJ
如果答案可以解決您的問題,請將其標記爲已接受。 – Monz
我很高興做到這一點,但我不明白...請指教! – JennyJ