62,620
社区成员
发帖
与我相关
我的任务
分享
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import javax.swing.*;
public class DrawFrame extends JFrame {
private static final long serialVersionUID = 1L;
JToolBar ToolBar=new JToolBar();
MyCanvas canvas=new MyCanvas();
LinkedList<Shape> ShapeList=new LinkedList<>();
int btNum=0;
public DrawFrame() {
setTitle("画板");
setBounds(100, 100, 500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
add(ToolBar, BorderLayout.NORTH);
add(canvas, BorderLayout.CENTER);
MakeButton("直线", 1);
MakeButton("矩形", 2);
MakeButton("圆形", 3);
MakeButton("椭圆", 4);
MakeButton("擦除", 5);
MakeButton("清除", 6);
MakeButton("选颜色", 7);
}
private void MakeButton(String text, int num) {
JButton bt=new JButton(text);
ToolBar.add(bt);
bt.addActionListener(event->btNum=num);
}
class MyCanvas extends Canvas{
private static final long serialVersionUID = 1L;
private double x1, x2, y1, y2;
private Color paintColor=Color.BLACK;
private Graphics g;
public MyCanvas() {
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
}
public void mouseReleased(MouseEvent e) {
x2=e.getX();
y2=e.getY();
g=getGraphics();
if(btNum==1) {
Shape list=new Line(x1, y1, x2, y2, paintColor);
list.draw(g);
ShapeList.add(list);
}
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
x2=e.getX();
y2=e.getY();
g=getGraphics();
if(btNum==0) {
Shape list=new Line(x1, y1, x2, y2, paintColor);
list.draw(g);
ShapeList.add(list);
x1=x2;
y1=y2;
}
else if(btNum==1) {
Shape list=new Line(x1, y1, x2, y2, paintColor);
list.draw(g);
}
if(btNum!=0) {
repaint();
}
}
});
}
public void paint(Graphics g){
for(Shape sh:ShapeList)
sh.draw(g);
}
}
public static void main(String[] args) {
new DrawFrame();
}
}