2014-06-26 41 views
2

不知道它是否是一个非常具体的标题,但我已经问过这个问题但已经死了。 我想执行paintComponent(),所以我可以绘制矩形,三角形和更多的类是一个JComponent。Java paintComponent作为JComponent

这是到目前为止我的代码:

public class Design extends JComponent { 
private static final long serialVersionUID = 1L; 

private List<ShapeWrapper> shapesDraw = new ArrayList<ShapeWrapper>(); 
private List<ShapeWrapper> shapesFill = new ArrayList<ShapeWrapper>(); 

GraphicsDevice gd =  GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); 
int screenWidth = gd.getDisplayMode().getWidth(); 
int screenHeight = gd.getDisplayMode().getHeight(); 

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D) g; 
    for(ShapeWrapper s : shapesDraw){ 
     g2d.setColor(s.color); 
     g2d.draw(s.shape); 
    } 
    for(ShapeWrapper s : shapesFill){ 
     g2d.setColor(s.color); 
     g2d.fill(s.shape); 
    } 
} 

public void drawRect(int xPos, int yPos, int width, int height) { 
    shapesDraw.add(new Rectangle(xPos, yPos, width, height)); 
    repaint(); 
} 

public void fillRect(int xPos, int yPos, int width, int height) { 
    shapesFill.add(new Rectangle(xPos, yPos, width, height)); 
    repaint(); 
} 

public void drawTriangle(int leftX, int topX, int rightX, int leftY, int topY, int rightY) { 
    shapesDraw.add(new Polygon(
      new int[]{leftX, topX, rightX}, 
      new int[]{leftY, topY, rightY}, 
      3)); 
    repaint(); 
} 

public void fillTriangle(int leftX, int topX, int rightX, int leftY, int topY, int rightY) { 
    shapesFill.add(new Polygon(
      new int[]{leftX, topX, rightX}, 
      new int[]{leftY, topY, rightY}, 
      3)); 
    repaint(); 
} 


public Dimension getPreferredSize() { 
    return new Dimension(getWidth(), getHeight()); 
} 

public int getWidth() { 
    return screenWidth; 
} 
public int getHeight() { 
    return screenHeight; 
} 

} 

class ShapeWrapper { 

    Color color; 
    Shape shape; 

    public ShapeWrapper(Color color , Shape shape){ 
     this.color = color; 
     this.shape = shape; 
    } 
} 

如上图所示,一切工作完全正常,除了能够选择一种颜色。 我想能够定义与他们各自的位置和长度的矩形和三角形,但也想添加一个颜色。

但我得到一个错误。

错误说:

的方法在类型列表中添加(ShapeWrapper)< ShapeWrapper>是不适用的参数(矩形)

和:

Add方法(ShapeWrapper)类型列表< ShapeWrapper>不适用于参数(多边形)

请帮忙!我非常强调试图弄清楚这一点,因为它阻止我做很多事情。

回答

4

答案是非常基本的... Shape不是一个类型的ShapeWrapper,因此它不能被添加到decalred为List<ShapeWrapper>

一个List你应该不是做的

shapesDraw.add(new Rectangle(xPos, yPos, width, height)); 
什么

是更多的东西一样......

shapesDraw.add(new ShapeWrapper(Color.BLACK, new Rectangle(xPos, yPos, width, height))); 

同样为您...Triangle方法。你需要用一个ShapeWrapper产生的Polygon试图将它添加到List

+1

你先生之前......吻我...... 它的工作原理,完美,无法谢谢你了。 – Sk4llsRPG

+1

除非你要买饮料......和很多饮料......)很高兴它的工作;) – MadProgrammer

+1

哈哈哈哈,是的。 原因是我可以简化我的代码,所以如果我把油漆放到JComponent中,它会简单得多,然后我可以直接将它添加到JPanel中。 再次感谢。 编辑: 我想你回答了我上周同班的其他问题:D – Sk4llsRPG