您好,我在将图像绘制到框架时遇到错误。我不确定这里出了什么问题。
我在这里得到以下错误。
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方法可见的类属性。请勿尝试使用此方法加载图像(或执行其他可能长时间运行的任务)。 JComponent
是ImageObserver
,因此g.drawImage(image, 0, 0, null);
应该是g.drawImage(image, 0, 0, this);
这是一个基于悉尼图像的示例(不,不是血腥的歌剧院-挑剔,挑剔..)。
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/