用Java编写窗体应用实现拉橡皮筋的手法绘图,能绘制直线、椭圆、矩形。通过3个按钮选择绘制的图形类型,通过鼠标按下确定起点,通过拖动进行绘制,释放鼠标完成绘制。
时间: 2024-03-22 22:42:42 浏览: 60
好的,下面是一个简单的Java窗体应用程序,可以实现你所描述的功能:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingApp extends JFrame implements MouseListener, MouseMotionListener {
private int startX, startY, endX, endY;
private boolean drawing;
private int shapeType;
private JPanel drawPanel;
public DrawingApp() {
super("Drawing App");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new JPanel();
drawPanel.setBackground(Color.WHITE);
drawPanel.addMouseListener(this);
drawPanel.addMouseMotionListener(this);
add(drawPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton lineButton = new JButton("Line");
JButton ovalButton = new JButton("Oval");
JButton rectButton = new JButton("Rectangle");
lineButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapeType = 0;
}
});
ovalButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapeType = 1;
}
});
rectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapeType = 2;
}
});
buttonPanel.add(lineButton);
buttonPanel.add(ovalButton);
buttonPanel.add(rectButton);
add(buttonPanel, BorderLayout.NORTH);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
drawing = true;
}
public void mouseDragged(MouseEvent e) {
endX = e.getX();
endY = e.getY();
drawPanel.repaint();
}
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
drawing = false;
drawPanel.repaint();
}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void paint(Graphics g) {
super.paint(g);
if (drawing) {
g.setColor(Color.BLACK);
switch (shapeType) {
case 0:
g.drawLine(startX, startY, endX, endY);
break;
case 1:
g.drawOval(Math.min(startX, endX), Math.min(startY, endY), Math.abs(endX - startX), Math.abs(endY - startY));
break;
case 2:
g.drawRect(Math.min(startX, endX), Math.min(startY, endY), Math.abs(endX - startX), Math.abs(endY - startY));
break;
}
}
}
public static void main(String[] args) {
new DrawingApp();
}
}
```
这个程序创建了一个窗体应用,包含一个画布和三个按钮用于选择要绘制的图形类型。当用户按下鼠标时,记录起始点坐标,并将“drawing”标记设置为true;当用户拖动鼠标时,计算当前图形的大小和位置,并实时绘制到画布上;当用户释放鼠标时,完成图形的绘制,将“drawing”标记设置为false。程序还重写了paint()方法,用于在画布上绘制当前正在绘制的图形。
需要注意的是,这个程序只是一个简单的示例,还有很多细节问题需要处理,比如如何实现拉橡皮筋效果、如何处理多个图形绘制等等,你可以根据自己的需求进行修改和完善。
阅读全文