求一个用JAVA写的最简单的画图工具;能画直线就行,其他不需要。

求一个用JAVA写的最简单的画图工具;能画直线就行,其他不需要。,第1张

import java.awt.BorderLayout

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编程工具,运行效果如下:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8129517.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存