首页 > 解决方案 > 不同的操作取决于选择的单选按钮

问题描述

class personalFrame {

    JTextField totalIncome = new JTextField(10);
    private JFrame frame3 = new JFrame("Personal Tax Calculator");
    JButton Calculate = new JButton("Calculate");
     JRadioButton residentTax = new JRadioButton("Resident Tax");
     JRadioButton nonresidentTax = new JRadioButton("Working Tax");
     JRadioButton workingTax = new JRadioButton("Non-working Tax");

    public personalFrame() {

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

        frame3.add(new JLabel("Total Income "));
        frame3.add(totalIncome);
        frame3.add(Calculate);
        frame3.add(residentTax);
        frame3.add(nonresidentTax);
        frame3.add(workingTax);

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

                String Income = totalIncome.getText();
                Double totalIncome = Double.parseDouble(Income);
                double expenseTax = 0;
                double totalTax = totalIncome - expenseTax;
                String Tax = String.valueOf(totalTax);
                JOptionPane.showMessageDialog(null, "Tax payable is A$" + Tax, "Total tax", JOptionPane.INFORMATION_MESSAGE);

            }

        });

           residentTax.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ie){
                double expenseTax = 1000;
            }
        });

           nonresidentTax.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ie){
                 double expenseTax = 1500;

            }
        });

           workingTax.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ie){
                 double expenseTax = 2000;

            }
        });

    }
}

上面的代码适用于我正在研究的计算税程序。该框架是用户可以选择的选项。在这里,他们可以输入总收入并计算税款(我尚未将此方法链接到此,现在它只是一个占位符计算,直到按钮 wokr)

我是 jswing 的新手,所以我对这些功能有点困惑。我希望计算器 ActionListener 中的双 eexpenseTax 等于用户选择的任何单选按钮(居民、非居民或工作税,每个都有自己的费用税变量)

如何实现这一目标?谢谢你

标签: javaswingradio-button

解决方案


JButton Calculate = new JButton("Calculate");

变量名不应以大写字符开头。始终如一!

double expenseTax = 0;
double totalTax = totalIncome - expenseTax;

上面的代码没有意义。费用税的值始终为零。

double expenseTax = 1000;

ActionListeners 中的代码也没有任何作用,您定义了一个“局部变量”,它不能在程序的其他任何地方使用。

所以解决方案是在你的类中使用“实例变量”。JRadioButton ActionListeners 将更新此变量。然后 JButton ActionListener 将在计算中使用这个变量。

因此,在您定义按钮的地方定义变量:

private couble expenseTax;

然后在 JRadioButton 侦听器中使用:

//double expenseTax = 1000;
expenseTax = 1000;

最后在您使用的 JButton ActionListener 中:

//double expenseTax = 0;
double totalTax = totalIncome - expenseTax;

推荐阅读