写一个画板程序 鼠标轨迹导致画板闪烁的问题

月球上的_人 2017-11-02 06:42:47
如果在已有的画面上再画东西,比如画直线,拖拽的直线轨迹会导致画面闪烁,试了网上说的双缓冲,本来直线的轨迹不会闪,只有画面闪,现在变成直线的轨迹也会闪烁了,请问要怎么解决?


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

public class DrawFrame extends JFrame {
private static final long serialVersionUID = 1L;
JToolBar ToolBar=new JToolBar();
MyCanvas canvas=new MyCanvas();
LinkedList<Shape> ShapeList=new LinkedList<>();
int btNum=0;

public DrawFrame() {
setTitle("画板");
setBounds(100, 100, 500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

add(ToolBar, BorderLayout.NORTH);
add(canvas, BorderLayout.CENTER);
MakeButton("直线", 1);
MakeButton("矩形", 2);
MakeButton("圆形", 3);
MakeButton("椭圆", 4);
MakeButton("擦除", 5);
MakeButton("清除", 6);
MakeButton("选颜色", 7);
}

private void MakeButton(String text, int num) {
JButton bt=new JButton(text);
ToolBar.add(bt);
bt.addActionListener(event->btNum=num);
}


class MyCanvas extends Canvas{
private static final long serialVersionUID = 1L;
private double x1, x2, y1, y2;
private Color paintColor=Color.BLACK;
private Graphics g;

public MyCanvas() {
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e)
{
x1=e.getX();
y1=e.getY();

}
public void mouseReleased(MouseEvent e) {
x2=e.getX();
y2=e.getY();
g=getGraphics();
if(btNum==1) {
Shape list=new Line(x1, y1, x2, y2, paintColor);
list.draw(g);
ShapeList.add(list);
}

}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
x2=e.getX();
y2=e.getY();
g=getGraphics();
if(btNum==0) {
Shape list=new Line(x1, y1, x2, y2, paintColor);
list.draw(g);
ShapeList.add(list);
x1=x2;
y1=y2;
}
else if(btNum==1) {
Shape list=new Line(x1, y1, x2, y2, paintColor);
list.draw(g);
}
if(btNum!=0) {
repaint();
}
}
});
}

public void paint(Graphics g){
for(Shape sh:ShapeList)
sh.draw(g);
}

}


public static void main(String[] args) {
new DrawFrame();
}
}
...全文
112 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧