Make a simple drawing board (straight line or rectangle)

Make a simple drawing board

Only the code for drawing straight lines and rectangles is demonstrated here, and the rest can be expanded freely


step:

1. Create a new form

2. Set the form properties

3. Add an action listener for the mouse

4. Create the MyListener class to inherit the interface class MouseListener

5. Get the coordinates of the mouse press and release point

6. Create a new brush to make the painting straight


surroundings:

eclipse under win8


package lessonPackage;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Draw extends JFrame
{
	public static void main(String[]args)
	{
		Draw db=new Draw();
		db.initFrame();
	}
	public void initFrame()
	{
		this.setTitle("画板");
		this.setSize(800,600);
		this.setLayout(new FlowLayout());
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(3);
		
		this.setVisible(true);
		//得到画笔,必须在窗体可见之后
		Graphics g=this.getGraphics();
		//安装监听器
		MyListener mouse=new MyListener(g);
		this.addMouseListener(mouse);
	}
}
package lessonPackage;
import java.awt.*;
import java.awt.event.*;
public class MyListener implements MouseListener
{
 public Graphics g1;
 public int x1,x2,y1,y2;
 //重载MyListener构造函数
 public MyListener(Graphics g)
 {
  g1=g;
 }
 /**
  * 鼠标按下时执行
  */
 public void mousePressed(MouseEvent e) 
 {
  //确定按下时坐标
  x1=e.getX();
  y1=e.getY();
 }
 /**
  * 鼠标释放时执行
  */
 public void mouseReleased(MouseEvent e) 
 {
  //确定释放时坐标
  x2=e.getX();
  y2=e.getY();
  //在按下和释放两点之间绘制图像,需要用画笔Graphics
  //g1.drawLine(x1, y1, x2, y2);
  int width=Math.abs(x2-x1);
  int height=Math.abs(y2-y1);
  int minX=Math.min(x1, x2);
  int minY=Math.min(y1, y2);
  g1.drawRect(minX, minY, width, height);
  
 }
 /**
  * 鼠标点击时执行
  */
 public void mouseClicked(MouseEvent e) 
 {
  
 }
 /**
  * 鼠标进入时执行
  */
 public void mouseEntered(MouseEvent e)
 {
  
 }
 /**
  * 鼠标出去时执行
  */
 public void mouseExited(MouseEvent e) 
 {
  
 }
 
}

Important knowledge points:

The relationship between ordinary classes, abstract classes, and interface classes

1. Ordinary classes can call the constructor to construct objects, but abstract classes and interface classes cannot, so usually interface classes and abstract classes are used as parent classes

2. Ordinary classes cannot call abstract methods, while abstract classes have abstract methods, and interface classes can only have abstract methods. Therefore, when inheriting abstract classes or

     For interface classes, ordinary classes need to override the abstract methods of the parent class

3. Ordinary classes can inherit multiple interfaces at the same time, but only one abstract class can be inherited at the same time


 



Guess you like

Origin blog.csdn.net/dream_18/article/details/51571225