我当前画的图形是currentShape(MyShape类型),一旦鼠标释放就表示画好了保存在Shapes数组里。我现在绘制前面已画好的图形没有问题,但是当前画的图形只有鼠标释放才能显示出来……
MyShape,我现在想用它的paintComponent画当前图形但好像此法不行,有什么其他办法吗?
publicclassMyShapeextendsJPanel{
intmyShapeType;//0:直线,1:椭圆,2:矩形
booleanmyFilled;
intx1,y1,x2,y2;
ColormyColor;
publicMyShape()//省略
publicMyShape(ColormyColor,intmyShapeType,booleanmyFilled,intx1,inty1,intx2,inty2)//省略
publicvoidPaint(intx2,inty2)//因为画直线第三四个参数是坐标而椭圆矩形是宽度高度所以这里根据形状修改下第三四个参数
{
switch(myShapeType)
{
case0:
this.x2=x2;
this.y2=y2;
break;
case1:
case2:
this.x2=x2-x1;
this.y2=y2-y1;
break;
}
}
publicvoidpaintComponent(Graphicsg)
{
super.paintComponent(g);
g.setColor(myColor);
if(!myFilled)
switch(myShapeType)
{
case0:
g.drawLine(x1,y1,x2,y2);
break;
case1:
g.drawOval(x1,y1,x2,y2);
break;
case2:
g.drawRect(x1,y1,x2,y2);
break;
}
else
switch(myShapeType)
{
case0:
g.drawLine(x1,y1,x2,y2);
break;
case1:
g.fillOval(x1,y1,x2,y2);
break;
case2:
g.fillRect(x1,y1,x2,y2);
break;
}
}
}
这是主绘图面板的鼠标事件:
publicclassDrawPanelextendsJPanel{
……//这个类的代码有省略
publicvoidmousePressed(MouseEventevent)
{
currentShape=newMyShape(currentColor,shapeType,filledShape,event.getX(),event.getY(),event.getX(),event.getY());
}
publicvoidmouseDragged(MouseEventevent)
{
currentShape.Paint(event.getX(),event.getY());//根据当前形状修改第三、四个参数x2,y2
currentShape.repaint();//!!!画当前的图形,为什么画不出???
repaint();//画以前的图形
}
publicvoidmouseReleased(MouseEventevent)
{
shapes[shapeCount]=newMyShape();
shapes[shapeCount]=currentShape;
shapeCount;
repaint();
}
publicvoidpaintComponent(Graphicsg)
{
super.paintComponent(g);
for(inti=0;ishapeCount;i)
{
g.setColor(shapes.myColor);
if(!shapes.myFilled)
switch(shapes.myShapeType)
{
case0:
g.drawLine(shapes.x1,shapes.y1,shapes.x2,shapes.y2);
break;
case1:
g.drawOval(shapes.x1,shapes.y1,shapes.x2,shapes.y2);
break;
case2:
g.drawRect(shapes.x1,shapes.y1,shapes.x2,shapes.y2);
break;
}
else
switch(shapes.myShapeType)
{
case0:
g.drawLine(shapes.x1,shapes.y1,shapes.x2,shapes.y2);
break;
case1:
g.fillOval(shapes.x1,shapes.y1,shapes.x2,shapes.y2);
break;
case2:
g.fillRect(shapes.x1,shapes.y1,shapes.x2,shapes.y2);
break;
}
}
}
}
|