[英]Java paintComponent as a JComponent
不知道这是否是一个非常具体的标题,但是我已经问过这个问题,但是已经死了。 我正在尝试执行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;
}
}
如上所示,除了能够选择一种颜色之外,其他所有功能都可以正常工作。 我希望能够定义矩形和三角形及其各自的位置和长度,还希望为其添加颜色。
但是我得到一个错误。
错误提示:
List <ShapeWrapper>类型中的方法add(ShapeWrapper)不适用于参数(Rectangle)
和:
List <ShapeWrapper>类型中的方法add(ShapeWrapper)不适用于参数(多边形)
请帮忙! 我非常想尝试解决这个问题,因为它阻碍了我执行许多操作。
答案是非常基本的... Shape
是不是一个类型的ShapeWrapper
,因此它不能被添加到List
decalred如List<ShapeWrapper>
你应该做什么而不是
shapesDraw.add(new Rectangle(xPos, yPos, width, height));
更像是...
shapesDraw.add(new ShapeWrapper(Color.BLACK, new Rectangle(xPos, yPos, width, height)));
您的...Triangle
方法也是如此。 您需要ShapeWrapper
生成的Polygon
包装在ShapeWrapper
然后再尝试将其添加到List
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.