Dan*_*ore -2 java user-interface swing scope compiler-errors
您好我在将图像绘制到我的框架上时出错.我不确定这里出了什么问题.
我在这里得到以下错误.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助都会很棒:)
几点.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1805 次 |
| 最近记录: |