java - 如何根据选择的按钮从类中调用方法?

标签 java swing user-interface

下面的代码计算通过 JTextField 给出的收入输入的税费。每个相应的类(ResidentTaxPayerForeignResidentTaxPayerWorkingTaxPayer)都有自己的方法,称为 calcTax()

下面的代码一直运行到计算的 ActionListener 为止。在此操作中,声明了一个字符串 - StringIncome - 并将其初始化为收入值,该收入值是 JTextField。然后将此JTextField 转换为 double 型并分配给一个 double 值:totalIncome。最后,JOptionPane.showMessageDialog() 用于调用 ResidentTaxPayer 类中的 calcTax() 方法。这将返回正确的计算。

如果只处理单个 Taxpayer 实例,到目前为止的代码是没问题的。不过,我设计的程序是使用 JButton 从 3 个可能的选择列表(实际上不是 ArrayList 只是为了避免混淆)中进行选择。我选择这样问我的问题是为了向大家展示我想要/为所有按钮输入的代码类型。

用于计算的 ActionListener 之后的代码仅更改所选按钮的消息标题。

我向大家提出的问题是如何编写我的程序,例如,如果选择了 residentTaxPayerButton,则收入将传递给 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";

            }
        });

    }
}

通用接口(interface)


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";

            }
        });

最佳答案

这里有不同的选项,但有一个共同的基础,即:

  • 在 Form 类上创建一个新字段,用于表示所需计算选项。
  • 使选择按钮的监听器将该字段设置为相应的表示形式
  • 让计算监听器评估字段并调用相应的方法。

你的老师不鼓励使用enum,我可以理解,但他们给了你一个非常糟糕的理由。无论如何,从技术上讲,您可以使用枚举。

您可以使用数值(例如 int )。在这种情况下,我会引入一些有据可查的 const int 值来表示选择。但这与使用枚举非常相似,因此他们也可能不赞成这样做。

还有更多,但我更喜欢的选项是:

让所有计算类实现一个通用接口(interface)。 然后使字段(我们称之为 calculationChoice)具有该接口(interface)类型。

选择按钮的监听器只需设置例如 calculationChoice = new ResidentTaxPayer(); 并且 Calculation 监听器甚至不必再关心,它只需调用 taxAmount =calculationChoice.calcTax(金额);

<小时/>

不相关:尝试使用 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;
    }
}

关于java - 如何根据选择的按钮从类中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094408/

相关文章:

java - hibernate 多对多加入条件

java - 如何终止消息中的边界

java - 在 jframe 中为 jpanel 调用 paintcomponent

java - 在 Java Swing 应用程序中实现 Spring Security

java - 将一个 JFrame 分配给另一个 JFrame

java - Java Swing 还在使用吗?

java - 当我旋转模拟器时,如何阻止我的 Activity 被破坏?

java - 列出用户输入

java - 带大圆圈的单选按钮组 Java

javascript - 自定义警报框不是 jquery 在哪里?