目录
N年前:__线条问题通过数组方法已经解决,但加载图片又出现问题。主要是闪屏。
翻出来改改旧博客
闪屏需要用双缓冲解决,当时主要想找到图片缓存为Image的方法
问题已全部解决
Form类包含鼠标移动监听:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class form extends JFrame {
Image img, img2;//用来缓冲的图片
static int width;
static int height;
static Mouse ms;
public static ArrayList<lines> ls;
public void launch() {
setTitle("repaint");
setLocation(300, 200);
this.addMouseListener(ms);
this.addMouseMotionListener(new mouseM());
new Thread(new PaintThread()).start();
}
static boolean once;//只执行一次
public void update(Graphics g) {
if (img2 == null) {
//img = this.createImage(width, height);
img2 = this.createImage(width, height);
}
if (img2 != null) {
g.drawImage(img2, 0, 0, this);
}
//gOffScreen.setColor(this.getBackground());
//gOffScreen.fillRect(0, 0, width, height);
//动态绘制
paint(g);
if (once && !ms.press) {
save(img2.getGraphics());//保存图片
once = false;
}
//g.drawImage(img, 0, 0, this); //把图片画到屏幕上
}
public void save(Graphics g) {//保存在画布上
g.setColor(Color.black);
// if (ls != null) {
// for (int i = 0; i < ls.size(); i++) {
// lines l = ls.get(i);
// g.drawLine(l.a, l.b, l.c, l.d);
// }
// }
lines l = ls.get(ls.size()-1);
g.drawLine(l.a, l.b, l.c, l.d);
}
public void paint(Graphics g) {//动态显示
if (ms.press) {
//System.out.println("ms:"+x1);
g.drawLine(ms.x0, ms.y0, x1, y1);
}
}
public static int x1, y1;
class mouseM extends MouseMotionAdapter {
form f;
@Override
public void mouseDragged(MouseEvent e) {
ms.press = true;
f.x1 = e.getX();
f.y1 = e.getY();
}
}
public static void main(String[] args) {
ls = new ArrayList<>();
ls.add(0,new form.lines(0, 0, x1, y1));
ms = new Mouse();
run = true;
System.out.println("hello");
form frame = new form();
width = 900;
height = 600;
frame.setSize(width, height);
frame.setVisible(true);
frame.launch();
}
public static class lines {
public int a, b, c, d;
public lines(int x0, int y0, int x1, int y1) {
a = x0;
b = y0;
c = x1;
d = y1;
}
public String getL() {
return a + "," + b + "," + c + "," + d;
}
}
private class PaintThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
rpaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
if (!run) {
break;
}
}
}
public void rpaint() {
update(getGraphics());
}
}
static boolean run;
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
run = false;
System.exit(0);
}
}
}
鼠标按键监听
import java.awt.event.*;
public class Mouse extends MouseAdapter {
public static int x0, y0, x1, y1;
public static boolean press;
form f;
public void mousePressed(MouseEvent e) {
this.x0 = e.getX();
this.y0 = e.getY();
}
public void mouseReleased(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
press = false;
f.once=true;
f.ls.set(0,new form.lines(x0, y0, x1, y1));
}
}