簡體   English   中英

不同的操作取決於選擇的單選按鈕

[英]Different Action depending on what radio button is chosen

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 等於用戶選擇的任何單選按鈕(居民、非居民或工作稅,每個都有自己的費用稅變量)

如何實現這一目標? 謝謝你

JButton Calculate = new JButton("Calculate");

變量名不應以大寫字符開頭。 始終如一!

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

上面的代碼沒有意義。 費用稅的值始終為零。

double expenseTax = 1000;

ActionListeners 中的代碼也沒有任何作用,您定義了一個“局部變量”,它不能在程序的其他任何地方使用。

所以解決方案是在 class 中使用“實例變量”。 JRadioButton ActionListeners 將更新此變量。 然后 JButton ActionListener 將在計算中使用這個變量。

因此,在您定義按鈕的地方定義變量:

private couble expenseTax;

然后在 JRadioButton 偵聽器中使用:

//double expenseTax = 1000;
expenseTax = 1000;

最后在您使用的 JButton ActionListener 中:

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

暫無
暫無

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

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