簡體   English   中英

這個簡單的GUI程序中的錯誤

[英]Error in this simple GUI program

這個簡單的程序應該能夠獲得加價百分比和批發成本並計算零售價,我將一個動作偵聽器置於“ 計算”按鈕上,但是當我按下“計算”按鈕時,將出現以下錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: 
For input string: "Enter the markup precentage" 
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) 
at java.lang.Double.parseDouble(Unknown Source) 
at mm$CalcListerner.actionPerformed(mm.java:58) 
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

有人可以幫我解決這個問題嗎?

有人可以解釋這些錯誤消息,因為我什么都沒得到嗎?

我的代碼是:

import javax.swing.*;
import java.awt.event.*;

public class mm extends JFrame {

    private JTextField WholesaleCost;
    private JTextField markupPresentage;
    private JLabel WCost;
    private JLabel MPrecentage;
    private JButton button;
    private JPanel pannel;
    private final int Width = 250;
    private final int height = 320;

    public mm() {
        setTitle("Retail Price Calculator");
        setSize(Width, height);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        buildPanel();
        add(pannel);
    }

    private void buildPanel() {
        WholesaleCost = new JTextField(10);
        markupPresentage = new JTextField(10);

        WCost = new JLabel("enter the Whole Sale cost");
        MPrecentage = new JLabel("Enter the markup precentage");

        button = new JButton("Calculate");
        button.addActionListener(new CalcListerner());

        pannel = new JPanel();
        pannel.add(WholesaleCost);
        pannel.add(markupPresentage);
        pannel.add(WCost);
        pannel.add(MPrecentage);
        pannel.add(button);
    }

    private class CalcListerner implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String WSaleinput;
            String MPres;
            WSaleinput = WholesaleCost.getText();
            MPres = MPrecentage.getText();

            double Value = Double.parseDouble(WSaleinput) * (Double.parseDouble(MPres) / 100);

            JOptionPane.showMessageDialog(null, "Retail Price is  " + Value);
        }
    }

    public static void main(String[] args) {
        mm x = new mm();
    }
}

您試圖將MPrecentage.getText()解析為雙精度,但這是標簽的值,而不是輸入的值。

您應該將MPres設置為markupPercentage.getText();

如果jvm無法從您提供的字符串中獲取數字,則會引發錯誤NumberFormatException。 在這種情況下,您嘗試解析文本“輸入標記比例”中的數字

您正在嘗試引用錯誤的組件。

這個

WSaleinput=WholesaleCost.getText();
MPres =MPrecentage.getText();

應該是

WSaleinput = WholesaleCost.getText();
MPres = markupPresentage.getText();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM