为什么paintComponent无法正确显示?

时间:2015-03-10 03:21:56

标签: java swing jpanel paintcomponent

运行我的程序时,有时会绘制三角形,有时它们不会,有时只显示最后一个。最初我把代码放在 for 循环中,但它没有用,所以我试着倒退并把它全部写出来,看看它是否有效,但无济于事。正确的行为应该是,在屏幕上显示等间距的五个三角形(直接在顶部矩形下方)。我尝试打印出数组,但调用 println()方法的次数是随机的,而不是常量。我听说Swing Framework可以随时调用 paintComponent()方法,但我不确定。基本上我问,为什么三角形(青色的)没有正确绘制,我该如何解决?

@SuppressWarnings("serial")
public class GraphicsClass extends JPanel {

    private int[] xCoordinates = {20, 40, 30};
    private int[] yCoordinates = {40, 40, 60};

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.setColor(Color.DARK_GRAY);
        g.fillRect(0, 0, 450, 40);
        g.fillRect(0, 260, 450, 40);

        g.setColor(Color.CYAN);
        g.fillPolygon(xCoordinates, yCoordinates, 3);
        xCoordinates[0] += 95;
        xCoordinates[1] += 95;
        xCoordinates[2] += 95;
        g.fillPolygon(xCoordinates, yCoordinates, 3);
        xCoordinates[0] += 95;
        xCoordinates[1] += 95;
        xCoordinates[2] += 95;
        g.fillPolygon(xCoordinates, yCoordinates, 3);
        xCoordinates[0] += 95;
        xCoordinates[1] += 95;
        xCoordinates[2] += 95;
        g.fillPolygon(xCoordinates, yCoordinates, 3);
        xCoordinates[0] += 95;
        xCoordinates[1] += 95;
        xCoordinates[2] += 95;
        g.fillPolygon(xCoordinates, yCoordinates, 3);
    }
}

1 个答案:

答案 0 :(得分:2)

以这种方式思考。可以随时调用paintComponent(在某些情况下,首次在屏幕上绘制组件时会超过四次)。因此,每次调用时,您都会95添加xCoordinates xCoordinates[0],这会使400等于paintComponent 800之后xCoordinates第二次调用public class TestPane extends JPanel { private int[] xCoordinates = {20, 40, 30}; private int[] yCoordinates = {40, 40, 60}; @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.DARK_GRAY); g.fillRect(0, 0, 450, 40); g.fillRect(0, 260, 450, 40); int[] xPosy = Arrays.copyOf(xCoordinates, xCoordinates.length); g.setColor(Color.CYAN); for (int index = 0; index < 4; index++) { g.fillPolygon(xPosy, yCoordinates, 3); xPosy[0] += 95; xPosy[1] += 95; xPosy[2] += 95; } } } ,第二次调用,等等第四次......

相反,您需要复制Shape并修改它,例如......

public class TestPane extends JPanel {

    private Polygon triangle;

    public TestPane() {
        triangle = new Polygon(new int[]{20, 40, 30}, new int[]{40, 40, 60}, 3);
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();

        g2d.setColor(Color.DARK_GRAY);
        g2d.fillRect(0, 0, 450, 40);
        g2d.fillRect(0, 260, 450, 40);

        g2d.setColor(Color.CYAN);
        AffineTransform at = AffineTransform.getTranslateInstance(0, 0);
        for (int index = 0; index < 4; index++) {

            Shape shape = at.createTransformedShape(triangle);
            g2d.fill(shape);
            at.translate(95, 0);

        }
    }
}

当然,你可以放弃一些奇怪的东西,只使用2D图形{{1}} API

{{1}}