您的位置:首页 > 编程语言 > Java开发

Java源码-简单的绘图板

2016-07-28 00:35 351 查看
看源码好处多多,边看边改效果更佳,可以了解每个细枝末节的来龙去脉。

通过修改参数,画笔的粗度已被我改的比较高了,落笔格外给力



遗留问题:看似简短的画图小程序,还没有完全理解代码为什么这么写,留待日后再察。

代码如下:

//Fig. 12.34: PaintPanel.java
//Adapter class used to implement event handlers.
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;

public class PaintPanel extends JPanel
{
// list Point references
private final ArrayList<Point> points = new ArrayList<>();

// set up GUI and register mouse event handler
public PaintPanel()
{
// handle frame mouse motion event
addMouseMotionListener(
new MouseMotionAdapter() // anonymous inner class
{
// store drag coordinates and repaint
@Override
public void mouseDragged(MouseEvent event)
{
points.add(event.getPoint());
repaint(); // repaint JFrame
}
}
);
}

// draw ovals in a 4-by-4 bounding box at specified locations on window
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); // clears drawing area

// draw all
for (Point point : points)
g.fillOval(point.x, point.y, 50, 50);
}

public static void main(String[] args)
{
// create JFrame
JFrame application = new JFrame("A simple paint program");

PaintPanel paintPanel = new PaintPanel();
application.add(paintPanel, BorderLayout.CENTER);

// create a label and place it in SOUTH of BorderLayout
application.add(new JLabel("Drag the mouse to draw"),
BorderLayout.SOUTH);

application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setSize(400, 200);
application.setVisible(true);
}
} // end class PaintPanel

运行截屏:(用鼠标描了十来次,总算描了一个比较满意的,送给Java)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: