java - 不同的操作取决于选择的单选按钮
问题描述
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 中的代码也没有任何作用,您定义了一个“局部变量”,它不能在程序的其他任何地方使用。
所以解决方案是在你的类中使用“实例变量”。JRadioButton ActionListeners 将更新此变量。然后 JButton ActionListener 将在计算中使用这个变量。
因此,在您定义按钮的地方定义变量:
private couble expenseTax;
然后在 JRadioButton 侦听器中使用:
//double expenseTax = 1000;
expenseTax = 1000;
最后在您使用的 JButton ActionListener 中:
//double expenseTax = 0;
double totalTax = totalIncome - expenseTax;
推荐阅读
- javascript - 如何在 express Router.route 和控制器模式中触发 next()?
- java - 如何使用 Proguard 删除 @Deprecated 注释?
- angular - Angular 网站在使用 firebase 添加管理员后将所有用户重定向到主页,包括管理员
- java - 面对应用程序崩溃(初学者)
- php - 用 php 呈现 MYSQL 嵌套的 JSON 对象
- javascript - 我的按钮没有改变功能
- python - 在python中将小数打印到8位精度?
- vbscript - ArcGIS 10.2 中的 VB 脚本错误,错误“13”,类型不匹配,使用应用程序时
- google-bigquery - 查询结果作为嵌套查询中的列名
- sql - SQL-满足条件时更改列的文本