在Graphics对象上绘图图像不起作用,但绘图线有效

时间:2014-12-06 15:46:39

标签: java swing awt

由于某些原因,绘制图像似乎不适用于我的Graphics对象,请参阅Triangle - > paintComponent()方法。

我可能会遗漏一些关键的东西吗?也许不将Graphics对象强制转换为Graphics2D?透明面膜?

    final JFrame jFrame = new JFrame();
    jFrame.add(new Triangle());
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setSize(500,500);
    jFrame.repaint();
    jFrame.setVisible(true);

三角类:

public class Triangle extends JPanel {

private int x = 50;
private int y = 50;

private int width = 100;
private int length = 300;

private int direction = 0;

private BufferedImage renderedImage = null;

private Image getRenderedImage() {
    if (renderedImage == null) {
        BufferedImage image = new BufferedImage(100, 300, BufferedImage.TYPE_3BYTE_BGR);
        drawGraphics(image.getGraphics());
    }

    return renderedImage;
}

private void drawGraphics(Graphics graphics) {
    graphics.setColor(Color.BLUE);
    // left
    graphics.drawLine(
            (int) Math.round(x - (width / 2.0)), y,
            (int) x, y + length);

    // right
    graphics.drawLine(
            (int) x, y + length,
            (int) Math.round(x + (width / 2.0)), y);

    // bottom
    graphics.drawLine(
            (int) Math.round(x - (width / 2.0)), y,
            (int) Math.round(x + (width / 2.0)), y);
}

protected void paintComponent(Graphics graphics) {
    // this works
    //drawGraphics(graphics);

    // this doesn't work
    graphics.drawImage(getRenderedImage(), 0, 0, null);
}
}

0 个答案:

没有答案
相关问题