簡體   English   中英

根據選擇的按鈕,如何從 class 調用方法?

[英]How do you call a method from a class depending on what button is chosen?

下面的代碼計算通過JTextField給出的收入輸入的稅。 每個相應的 class ( ResidentTaxPayerForeignResidentTaxPayerWorkingTaxPayer )都有自己的稱為calcTax()的方法。

下面的代碼一直有效,直到用於計算的ActionListener 在這個動作中,一個字符串 - StringIncome - 被聲明並初始化為一個收入值,它是一個JTextField 然后將此JTextField轉換為雙精度並分配給雙精度值: totalIncome 最后使用JOptionPane.showMessageDialog()調用ResidentTaxPayer class 中的calcTax()方法。 這將返回正確的計算。

如果只處理單個 Taxpayer 實例,那么到目前為止的代碼都很好。 但是,我已經設計了我的程序以使用JButton從列表中進行選擇(實際上不是ArrayList ,所以沒有人會感到困惑)3 種可能的選擇。 我選擇這樣問我的問題,以向所有人展示我想要/為所有按鈕輸入的那種代碼。

我在計算的ActionListener之后的代碼只會更改所選按鈕的消息標題。

我對你們所有人的問題是如何編寫我的程序,例如,如果選擇了residentTaxPayerButton ,那么收入將傳遞給 class 中的calcTax()方法並完成適當的計算。 但是如果選擇了NonResidentTaxPayer按鈕,那么收入就會被傳遞,因此它的calcTax()方法和適當的計算就會完成。

isSelect()方法在這里合適嗎? 或者您是否需要從按鈕偵聽器中調用該方法?

以防萬一有人問,類的相應代碼與問題無關。 這是我的 GUI 的問題,而不是納稅人的問題。 這些類可以在不使用 GUI 的情況下正常工作。


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

class personalFrame {

    private String title = "";
    JTextField Income = new JTextField(10);
    private JFrame personalTaxFrame = new JFrame("Personal Tax Calculator");
    JButton Calculate = new JButton("Calculate");

    ButtonGroup Tax = new ButtonGroup();
    JRadioButton residentTax = new JRadioButton("Resident Tax");
    JRadioButton nonresidentTax = new JRadioButton("Non-Resident Tax");
    JRadioButton workingTax = new JRadioButton("Working Tax");

    public personalFrame() {

        personalTaxFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        personalTaxFrame.setSize(300, 100);
        personalTaxFrame.setVisible(true);
        personalTaxFrame.setLayout(new FlowLayout());

        personalTaxFrame.add(new JLabel("Total Income "));

        personalTaxFrame.add(Income);
        personalTaxFrame.add(Calculate);

        Tax.add(residentTax);
        personalTaxFrame.add(residentTax);

        Tax.add(nonresidentTax);
        personalTaxFrame.add(nonresidentTax);

        Tax.add(workingTax);
        personalTaxFrame.add(workingTax);

        Calculate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String stringIncome = Income.getText();
                Double totalIncome = Double.parseDouble(stringIncome);
                JOptionPane.showMessageDialog(null, "Tax payable is A$" + ResidentTaxPayer.calcTax(totalIncome), title, JOptionPane.INFORMATION_MESSAGE);

            }

        });

        residentTax.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {

                title = "Resident Tax";


            }
        });

        nonresidentTax.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {

                title = "Non-resident Tax";

            }
        });

        workingTax.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {

                title = "Working Tax";

            }
        });

    }
}

通用接口


public interface TaxProfile {

    double getPayableTax();
    public String getTaxID();
    public String getNameOfTaxPayer();
}
    TaxProfile taxProfile;//create TaxProfileField


    residentTax.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
                taxProfile.getPayableTax(); //use field to call interface method
                title = "Resident Tax";

            }
        });

這里有不同的選擇,在一個共同的基礎上工作,即:

  • 在表格 class 上創建一個新字段,其中包含所需計算選項的表示。
  • 使選擇按鈕的偵聽器將該字段設置為相應的表示
  • 讓計算監聽器評估字段並調用相應的方法。

你的老師不鼓勵使用enum ,我可以理解,但他們給了你一個非常糟糕的理由。 無論如何,從技術上講,您可以使用枚舉。

您可以使用數值(例如int )。 在這種情況下,我會引入一些有據可查的const int值來表示選擇。 但這與使用枚舉非常相似,因此他們也可能不贊成這一點。

還有更多,但我更喜歡的選項是:

讓所有計算類實現一個通用interface 然后使該字段(我們稱其為calculationChoice )具有該接口類型。

然后,選擇按鈕的偵聽器將設置為例如calculationChoice = new ResidentTaxPayer(); 並且計算監聽器甚至不必再關心了,它只需調用taxAmount = calculationChoice.calcTax(amount);


不相關:嘗試使用 BigDecimal 而不是 double 並使用兩種類型的不同輸入記錄結果並進行比較。 我猜你會感到驚訝。


例子

public class HelloWorld{

     public static void main(String []args){
         // ResidentTaxPayer is-a TaxProfile, so we can assign it like so:
         TaxProfile taxProfile = new ResidentTaxPayer();
        System.out.println("Payable Amount in US $: " + taxProfile.getPayableTaxAmount(5432.10));
         // so is NonResidentTaxPayer, so this is also valid
         taxProfile = new NonResidentTaxPayer();
        System.out.println("Payable Amount in US $: " + taxProfile.getPayableTaxAmount(5432.10)); // different result!
     }
}

public interface TaxProfile{
    double getPayableTaxAmount( double income );
}

public class ResidentTaxPayer implements TaxProfile {
    public double getPayableTaxAmount( double income )
    {
        double tax = 0.0;
        // calculate tax
        tax = income * 0.18; // Just a dummy
        return tax;
    }
}

public class NonResidentTaxPayer implements TaxProfile {
    public double getPayableTaxAmount( double income )
    {
        double tax = 0.0;
        // calculate tax
        tax = income * 0.24; // Just a dummy
        return tax;
    }
}

暫無
暫無

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

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