我正在尝试通过使用bufferedimage在jpanel中绘制一些形状(线,圆,矩形)。 所以我尝试了belove代码。它可以缓冲形状,但是问题是通过拖动鼠标可以像绘制每帧一样绘制形状。
这是代码`
public class PanelClass extends JPanel {
BufferedImage img;
int x1,y1,x2,y2,StarterX,StarterY, h,w;
static int flag;
Graphics2D g2d ;
public PanelClass() {
MouseHandler handler = new MouseHandler();
this.addMouseListener(handler);
this.addMouseMotionListener(handler);
我在这里做了一个bufferedimage对象
img = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) img.getGraphics();
}
这些部分仅仅是因为获得了鼠标事件起点的坐标
public void starter(int oldX,int oldY){
x1 = oldX;
y1 = oldY;
}
public void finisher(int currentX,int currentY){
x2 = currentX;
y2 = currentY;
if(x1 > x2){
StarterX = x2;
}
else if(x2 > x1){
StarterX = x1;
}
if(y1 > y2){
StarterY = y2;
}
else if(y2 > y1){
StarterY = y1;
}
}
public int Diameter(int oldX,int oldY,int currentX,int currentY){
return (int) Math.sqrt ( (Math.pow(currentX - oldX, 2)) + (Math.pow(currentY - oldY, 2) ) ) ;
}
此方法获取绘制的坐标和顺序。(这只是为了使代码清晰一些,我在paintComponent()上使用了此方法)
public void painter(){
if(flag ==1){
g2d.setColor(Color.ORANGE);
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawOval(StarterX ,StarterY,Diameter(x1, y1, x2, y2),Diameter(x1, y1, x2, y2));
g2d.setBackground(Color.YELLOW);
}
else if(flag == 2){
//fill oval;
g2d.setColor(Color.ORANGE);
g2d.setBackground(Color.YELLOW);
g2d.fillOval(StarterX ,StarterY,Diameter(x1, y1, x2, y2),Diameter(x1, y1, x2, y2) );
}
else if (flag == 3){
g2d.setColor(Color.ORANGE);
g2d.setStroke(new BasicStroke(3.0f));
g2d.drawRect(StarterX, StarterY,Math.abs(x2-x1) ,Math.abs(y2-y1));
g2d.setBackground(Color.YELLOW);
}
else if (flag == 4){
g2d.setColor(Color.ORANGE);
g2d.fillRect(StarterX, StarterY,Math.abs(x2-x1) ,Math.abs(y2-y1));
g2d.setBackground(Color.YELLOW);
}
else if (flag == 5){
g2d.setColor(Color.ORANGE);
g2d.setStroke(new BasicStroke(5.0f));
g2d.drawLine(x1, y1,x2,y2);
g2d.setBackground(Color.YELLOW);
}
}
public void flagSetter(int flag){
this.flag = flag;
}
at this method i used g.drawImage()
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
painter();
g.drawImage(img, 0,0, null);
}
class MouseHandler implements MouseListener,MouseMotionListener{
@Override
public void mousePressed(MouseEvent e) {
starter(e.getX(),e.getY());
}
@Override
public void mouseReleased(MouseEvent e) {
finisher(e.getX(),e.getY());
g2d.drawImage(img,0,0 ,null);
repaint();
if(flag == 1){
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
finisher(e.getX(),e.getY() );
// System.out.printf("%d %d ",currentX,currentY);
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
}
}`
我真的不知道为什么会这样