import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Point
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.MouseMotionAdapter
import java.awt.geom.Line2D
import java.util.Vector
import javax.swing.JFrame
import javax.swing.JPanel
class LinePanel extends JPanel{
private static final long serialVersionUID = 1L
private Vector<Line2D>lines = new Vector<Line2D>()//存储画板上所有的直线
private Line2D line = new Line2D.Double()
private Line2D cur = new Line2D.Double() //起点到当前光标的直线
public LinePanel(){
super()
this.setBackground(new Color(255,255,255))
}
public void setLines(Vector<Line2D>lines){
this.lines = lines
}
public void setCur(Line2D cur){
this.cur =cur
}
@Override
public void paint(Graphics g){
super.paint(g)
Graphics2D g2d = (Graphics2D) g
for(Line2D l2d:lines){
line = l2d
g2d.draw(line)
}
if(cur!=null){
g2d.draw(cur)
}
}
}
public class DrawLine extends JFrame{
private static final long serialVersionUID = 1L
private LinePanel panel
private Vector <Line2D>lines
private Point start
public DrawLine(){
panel= new LinePanel()
lines = new Vector<Line2D>()
this.setBounds(100, 200, 400, 400)
this.setLayout(new BorderLayout())
this.add(panel,BorderLayout.CENTER)
this.setPanelListener()
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
this.setVisible(true)
}
private void setPanelListener() {
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
start = new Point(e.getX(),e.getY())
}
@Override
public void mouseReleased(MouseEvent e) {
Line2D line = new Line2D.Double(start.x,start.y,e.getX(),e.getY())
lines.add(line)
panel.setLines(lines)
line = null
}
})
panel.addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e) {
panel.setCur(new Line2D.Double(start.x,start.y,e.getX(),e.getY()))
panel.repaint()
}
})
}
public static void main(String[] args) {
new DrawLine()
}
}
使用java画圆要用到绘图类Graphics,下面是实例代码和运行效果:
package com.dikea.demo01
import java.awt.*
import javax.swing.*
// java绘图原理
public class demo_01 extends JFrame {
MyPanel mp = null
public static void main(String[] args) {
// TODO 自动生成的方法存根
demo_01 demo01 = new demo_01()
}
public demo_01(){
mp = new MyPanel()
this.add(mp)
this.setSize(400, 300)
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
this.setVisible(true)
}
}
// 定义一个MyPanel面板,用于绘图区域
class MyPanel extends JPanel{
//覆盖JPanel
// Graphics 是绘图的重要类,可以理解成一支画笔
public void paint(Graphics g){
// 1. 调用父类函数完成初始化任务
// 这句话不可以少
super.paint(g)
// 先画出一个圆圈
g.drawOval(100, 100, 30, 30)
}
}
代码复制进ide编程工具,运行效果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)