Java设置一个简单页面 质量和重力 第一个按钮质量转重力 第二个按钮重力转质量 第三个清除
时间: 2024-02-04 17:03:23 浏览: 28
好的,以下是一个简单的Java页面,包含三个按钮:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WeightGravityConverter extends JFrame implements ActionListener {
private JLabel label1, label2;
private JTextField textField1, textField2;
private JButton button1, button2, button3;
public WeightGravityConverter() {
setTitle("Weight-Gravity Converter");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new JLabel("Weight:");
textField1 = new JTextField(10);
label2 = new JLabel("Gravity:");
textField2 = new JTextField(10);
button1 = new JButton("Weight to Gravity");
button2 = new JButton("Gravity to Weight");
button3 = new JButton("Clear");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
JPanel panel1 = new JPanel();
panel1.add(label1);
panel1.add(textField1);
panel1.add(label2);
panel1.add(textField2);
JPanel panel2 = new JPanel();
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(panel1, BorderLayout.CENTER);
contentPane.add(panel2, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
String input = textField1.getText();
double weight = Double.parseDouble(input);
double gravity = weight * 9.8;
textField2.setText(String.format("%.2f", gravity));
} else if (e.getSource() == button2) {
String input = textField2.getText();
double gravity = Double.parseDouble(input);
double weight = gravity / 9.8;
textField1.setText(String.format("%.2f", weight));
} else if (e.getSource() == button3) {
textField1.setText("");
textField2.setText("");
}
}
public static void main(String[] args) {
WeightGravityConverter converter = new WeightGravityConverter();
converter.setVisible(true);
}
}
```
这个页面包含两个文本框和三个按钮,用于将重量和重力互相转换,以及清除文本框中的内容。按钮的功能分别是:
- 将文本框中的重量转换为重力,并在另一个文本框中显示结果。
- 将文本框中的重力转换为重量,并在另一个文本框中显示结果。
- 清空文本框中的内容。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)