Java画笔的简单实用方法

时间:2021-12-06 03:24:04

        Java中提供了画笔,可以使用画笔做出界面上的任何东西,接下来先熟悉一下画笔的使用过程,以画一条线为例。

源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
 
/**
 * 画笔的初始用
 *
 * @author M_WBCG
 *
 */
public class paintBrush extends JFrame implements MouseListener {
    // 画笔初始化
    Graphics g;
    // 坐标的起点和终点的初始化
    int x1, y1, x2, y2;
 
    public paintBrush() {
        // TODO Auto-generated constructor stub
        // 创建获得画笔的面板
        JPanel drawPanel = new JPanel();
        // 给窗体添加面板
        add(drawPanel);
        setTitle("画笔");
        setSize(500, 500);
        setVisible(true);
        // 画笔获取要在可见之后,设置成全局属性
        g = drawPanel.getGraphics();
        drawPanel.addMouseListener(this);
    }
 
    public static void main(String[] args) {
        new paintBrush();
    }
 
    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        x1 = e.getX();
        y1 = e.getY();
    }
 
    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        x2 = e.getX();
        y2 = e.getY();
        g.drawLine(x1, y1, x2, y2);
        x1 = x2 = y1 = y2 = 0;
    }
 
    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
 
    }
}

        在此就可以引申出很多的问题,怎样在一边画线的时候就可以看到线的形成?怎样去画一条直线?在画完一条直线后最小化该程序后重新打开线段消失?怎样在画完直线后关闭掉程序第二次打开还存在?

        以上就是本文的全部内容,希望对大家有所帮助!

原文链接:http://m.blog.csdn.net/M_WBCG/article/details/60140292