用Java编写窗体应用实现拉橡皮筋的手法绘图,能绘制直线、椭圆、矩形。通过3个按钮选择绘制的图形类型,通过鼠标按下确定起点,通过拖动进行绘制,释放鼠标完成绘制。
时间: 2024-03-22 10:42:49 浏览: 127
好的,这是一个关于Java编写窗体应用的问题,我会尽力回答。首先,我们需要创建一个Java窗体应用程序,可以使用Swing或JavaFX等库来实现。然后,我们需要创建一个画布来绘制图形。以下是一个简单的示例程序,它可以绘制直线、椭圆和矩形:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawingApp extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel canvas;
private JButton lineButton, ovalButton, rectButton;
private Point startPoint, endPoint;
public DrawingApp() {
setTitle("Drawing App");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
setVisible(true);
}
private void initComponents() {
lineButton = new JButton("Line");
ovalButton = new JButton("Oval");
rectButton = new JButton("Rectangle");
canvas = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (startPoint != null && endPoint != null) {
int x1 = startPoint.x, y1 = startPoint.y, x2 = endPoint.x, y2 = endPoint.y;
if (lineButton.isSelected()) {
g.drawLine(x1, y1, x2, y2);
} else if (ovalButton.isSelected()) {
g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
} else if (rectButton.isSelected()) {
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
}
}
}
};
canvas.setBackground(Color.WHITE);
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
endPoint = null;
canvas.repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
endPoint = e.getPoint();
canvas.repaint();
}
});
canvas.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
endPoint = e.getPoint();
canvas.repaint();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(lineButton);
buttonPanel.add(ovalButton);
buttonPanel.add(rectButton);
getContentPane().add(buttonPanel, "North");
getContentPane().add(canvas, "Center");
}
public static void main(String[] args) {
new DrawingApp();
}
}
```
在这个程序中,我们创建了一个JFrame窗口,并在其中放置了一个画布和三个按钮。当用户点击按钮时,我们记录所选图形类型,并在画布上绘制该图形。用户可以使用鼠标按下并拖动来绘制图形。当用户释放鼠标时,我们绘制最终的形状。
希望这个示例程序可以帮助你开始实现拉橡皮筋的手法绘图应用程序。如果你有任何疑问,请随时问我。
阅读全文