gpt4 book ai didi

java - Java图形编程绘制图像错误

转载 作者:行者123 更新时间:2023-12-02 11:11:28 25 4
gpt4 key购买 nike

您好,我在将图像绘制到框架时遇到错误。我不确定这里出了什么问题。

我在这里得到以下错误。

Java: 77: cannot find symbol
symbol: variable image
location: class DrawComponent
g.drawImage(image, 0, 0, null);


class DrawComponent extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// draw a circle with the same center
double centerX = 250;
double centerY = 180;
double radius = 20;

Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.setPaint(Color.RED);
g2.fill(circle);
g2.draw(circle);

String filename = "SydneyOperaHouse.jpeg";
try{
Image image = ImageIO.read(new File(filename));
}catch(IOException ex){
// Handle Exeption
}

g.drawImage(image, 0, 0, null);

}
}

任何帮助将是巨大的:)

最佳答案

几点。

  • 解决属性范围的问题。 应当将image属性传递(或加载到)构造函数中,并存储为paint方法可见的类属性。请勿尝试使用此方法加载图像(或执行其他可能长时间运行的任务)。
  • 在部署时,BG的图像通常将是嵌入式资源,因此可以通过URL访问它。
  • JComponentImageObserver,因此g.drawImage(image, 0, 0, null);应该是
    g.drawImage(image, 0, 0, this);
  • 我怀疑在0x0处绘制的图像应该在绘制红色椭圆之前(之前完成),否则它将绘制在其上方。

  • 这是一个基于悉尼图像的示例(不,不是血腥的歌剧院-挑剔,挑剔..)。
    import java.awt.*;
    import java.awt.geom.Ellipse2D;
    import javax.swing.*;
    import javax.imageio.ImageIO;
    import java.net.URL;

    public class DrawComponent extends JComponent {

    private Image image;

    DrawComponent(Image image) {
    this.image = image;
    Dimension d = new Dimension(image.getWidth(this),image.getHeight(this));
    this.setPreferredSize(d);
    }
    public void paintComponent(Graphics g) {
    // always call super first, to get borders etc.
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;

    // paint the BG
    g.drawImage(image, 0, 0, this);

    // draw a circle with the same center
    double centerX = 250;
    double centerY = 180;
    double radius = 20;

    Ellipse2D circle = new Ellipse2D.Double();
    circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
    g2.setPaint(Color.RED);
    g2.fill(circle);
    g2.draw(circle);
    }

    public static void main(String[] args) throws Exception {
    String s = "http://pscode.org/media/citymorn1.jpg";
    final Image image = ImageIO.read(new URL(s));
    Runnable r = new Runnable() {
    @Override
    public void run() {
    JComponent gui = new DrawComponent(image);
    JOptionPane.showMessageDialog(null, gui);
    }
    };
    SwingUtilities.invokeLater(r);
    }
    }

    关于java - Java图形编程绘制图像错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893416/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com