用java编写一个图形界面的程序,计算平面上任意给定的两个点的距离。(要求:通过图形界面给入两个点坐标,计算后用消息框输出其距离)
时间: 2024-02-08 15:11:25 浏览: 48
好的,以下是 Java 代码实现:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DistanceCalculator {
private JFrame frame;
private JLabel label1, label2;
private JTextField field1, field2;
private JButton button;
public DistanceCalculator() {
frame = new JFrame("距离计算器");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new JLabel("点A(x,y):");
label1.setBounds(20, 20, 60, 30);
frame.add(label1);
field1 = new JTextField();
field1.setBounds(100, 20, 150, 30);
frame.add(field1);
label2 = new JLabel("点B(x,y):");
label2.setBounds(20, 60, 60, 30);
frame.add(label2);
field2 = new JTextField();
field2.setBounds(100, 60, 150, 30);
frame.add(field2);
button = new JButton("计算距离");
button.setBounds(100, 100, 100, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateDistance();
}
});
frame.add(button);
frame.setLayout(null);
frame.setVisible(true);
}
private void calculateDistance() {
String[] point1 = field1.getText().split(",");
String[] point2 = field2.getText().split(",");
double distance = Math.sqrt(Math.pow(Integer.parseInt(point1[0])-Integer.parseInt(point2[0]), 2) + Math.pow(Integer.parseInt(point1[1])-Integer.parseInt(point2[1]), 2));
JOptionPane.showMessageDialog(frame, "点A和点B的距离为:" + String.format("%.2f", distance));
}
public static void main(String[] args) {
DistanceCalculator app = new DistanceCalculator();
}
}
```
这个程序使用了 Swing 库创建了一个简单的 GUI,包括两个文本框用于输入点 A 和点 B 的坐标,以及一个按钮用于计算距离。当用户点击按钮时,程序将获取用户输入的点坐标,并计算它们之间的距离。最后,距离结果将用消息框展示给用户。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)