写一个工资计算器界面的java代码
时间: 2024-09-15 11:07:50 浏览: 54
在Java中创建一个简单的工资计算器界面,我们可以使用Swing库来构建图形用户界面(GUI)。以下是一个基本的例子,包含一个文本框用于输入基础工资、加班小时数和税率,以及按钮用于计算总工资:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SalaryCalculator extends JFrame {
private JTextField baseSalaryField;
private JTextField overtimeHoursField;
private JTextField taxRateField;
private JButton calculateButton;
private JLabel resultLabel;
public SalaryCalculator() {
setTitle("工资计算器");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建布局管理器
JPanel panel = new JPanel(new GridLayout(4, 2));
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
// 添加输入字段
baseSalaryField = new JTextField();
overtimeHoursField = new JTextField();
taxRateField = new JTextField();
baseSalaryField.setColumns(10);
overtimeHoursField.setColumns(10);
taxRateField.setColumns(10);
// 添加计算按钮
calculateButton = new JButton("计算");
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double baseSalary = Double.parseDouble(baseSalaryField.getText());
int overtimeHours = Integer.parseInt(overtimeHoursField.getText());
double taxRate = Double.parseDouble(taxRateField.getText());
double overtimePay = overtimeHours * (baseSalary / 8); // 假设加班费按标准工资计算
double totalPayBeforeTax = baseSalary + overtimePay;
double taxAmount = totalPayBeforeTax * taxRate / 100;
double netPay = totalPayBeforeTax - taxAmount;
resultLabel.setText("净工资: " + netPay);
}
});
// 添加结果显示标签
resultLabel = new JLabel("结果: ");
resultLabel.setForeground(Color.BLUE);
// 将组件添加到面板上
panel.add(new JLabel("基础工资:"));
panel.add(baseSalaryField);
panel.add(new JLabel("加班小时:"));
panel.add(overtimeHoursField);
panel.add(new JLabel("税率:"));
panel.add(taxRateField);
panel.add(calculateButton);
panel.add(resultLabel);
setContentPane(panel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new SalaryCalculator();
});
}
}
```
在这个例子中,用户需要在文本框中输入基础工资、加班小时数和税率,点击“计算”按钮后,程序会根据输入值计算出税前工资和净工资,并显示在结果标签中。
阅读全文