我被困在一个项目中,我必须实现一系列最终形成功能绘图程序的几个类。我的问题是运行测试程序时绘图无法正常工作。为了给你一个基本的想法,我实现了MyLine, MyRectangle, MyOval
所有形状的子类 superclass MyShape
。这些子类中的每一个都实现了自己的draw
方法,该方法将 Graphics 参数作为参数。然后我实现了两个类来设计可以使用鼠标在其上绘制这些形状的界面。这两个类,DrawPanel
和,分别DrawFrame
扩展JPanel
和JFrame
。
我有一种感觉,错误出在 的重写paintComponent
方法中DrawPanel
,或者在repaint()
调用方法的方式中。当我运行程序时会发生什么,整个窗口会正确显示所有菜单等,但是当我尝试绘制形状时会发生以下两种情况之一:
- 屏幕上什么也没有发生。
- 如果我真的快速移动鼠标,我可能会得到一些颜色和形状正确的小涂鸦。
另外,我注意到如果我添加super.paintComponent(g2)
命令,我会得到正确的白色背景,我可以看到形状被拖出非常快,但它们实际上从未留在屏幕上。
这是我的代码DrawPanel
,我很确定这是发生错误的地方:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicTabbedPaneUI.MouseHandler;
public class DrawPanel extends JPanel {
private MyShape[] shapes;
private int shapeCount;
private int shapeType;
private MyShape currentShape;
private Color currentColor;
private boolean filledShape;
private JLabel statusLabel;
private Graphics gTest;
DrawPanel(JLabel P){
shapes= new MyShape[100];
shapeCount=0;
statusLabel=P;
currentColor= Color.black;
currentShape=null;
setBackground(Color.white);
shapeType=1;
Mouse handler= new Mouse();
addMouseListener(handler);
addMouseMotionListener(handler);
}
@Override
protected
void paintComponent(Graphics g2){
super.paintComponent(g2);
while(shapeCount>1 && currentShape!=null)
{
currentShape.draw(g2);
shapeCount--;
}
}
//set methods
void setColor(Color c){
currentColor=c;
}
void setFill(boolean f){
filledShape= f;
}
void setShape(int s){
shapeType=s;
}
void clearLastShape(){
if(shapeCount==0)
System.out.print("There are no more shapes to clear");
else
shapeCount--;
repaint();
}
void clearDrawing(){
shapeCount=0;
repaint();
}
class Mouse extends MouseAdapter implements MouseMotionListener{
@Override
public
void mousePressed(MouseEvent e){
if(shapeType==1)
currentShape= new MyLine();
else if(shapeType==2)
currentShape= new MyRectangle();
else
currentShape= new MyOval();
currentShape.setX1(e.getX());
currentShape.setY1(e.getY());
currentShape.setColor(currentColor);
if(shapeType==2 || shapeType==3){
((MyBoundedShape) currentShape).setFill(filledShape);
}
}
@Override public void mouseReleased(MouseEvent e){
currentShape.setX2(e.getX());
currentShape.setY2(e.getY());
shapes[shapeCount]=currentShape;
shapeCount++;
currentShape=null;
repaint();
}
@Override
public void mouseMoved(MouseEvent e){
statusLabel.setText("("+e.getX()+","+e.getY()+")");
}
@Override
public void mouseDragged(MouseEvent e){
mouseMoved(e);
currentShape.setX2(e.getX());
currentShape.setY2(e.getY());
repaint();
}
}
}
任何帮助表示赞赏。