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;
}
});
}
}
上面的代码适用于正在运行的Calculate Tax程序。该框架是用户可以选择的选项。在这里,他们可以输入总收入并计算出税金(目前尚未将方法链接到此,现在仅是占位符计算,直到按钮wokr为止)
我不是jswing的新手,所以我对功能有些困惑。我希望计算器ActionListener中的double eexpenseTax等于用户选择的任何单选按钮(居民,非居民或工作税,每个都有其自己的expenseTax varialbe)
如何实现这一目标?谢谢
最佳答案
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;
关于java - 根据选择的单选按钮的不同 Action ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58006157/