Java 在图形对象上绘制图像不起作用,但绘制线起作用
由于某些原因,在图形对象上绘制图像似乎不起作用,请参见Triangle->paintComponent()方法 我会错过一些重要的东西吗?也许与不将图形对象强制转换为Graphics2D有关?透明面具Java 在图形对象上绘制图像不起作用,但绘制线起作用,java,swing,awt,Java,Swing,Awt,由于某些原因,在图形对象上绘制图像似乎不起作用,请参见Triangle->paintComponent()方法 我会错过一些重要的东西吗?也许与不将图形对象强制转换为Graphics2D有关?透明面具 final JFrame jFrame = new JFrame(); jFrame.add(new Triangle()); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setSize
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);
}
}
不要使用
buffereImage=
尝试执行renderImage=
。您将返回renderImage
,该值为空,这就是正在绘制的内容,修复了它。谢谢您!