我试图通过文件路径显示图像。我在我的src文件夹中有图像,我尝试了5种不同类型的代码。
忽略已注释掉的代码,这些只是我正在绘制测试的形状
我已经尝试了文件路径和文件名,但没有任何效果。它没有给我任何错误或任何错误。
public void ImagePanel() {
try {
image = ImageIO.read(new File("BMan.jpg"));
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
JPanel panel = new MyPanel();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
//g.setColor(Color.RED);
//g.fillOval(CircleX, CircleY, CircleH, CircleW);
//g.setColor(Color.GREEN);
//g.fillRect(SquareX, SquareY, SquareW, SquareH);
g.drawImage(image, 50, 50, this);
}
答案 0 :(得分:0)
以下是我对该组件的实现:
public class ImageView extends JComponent
implements ComponentListener {
private static final long serialVersionUID = 3761966077344495154L;
private BufferedImage image;
private int imageX;
private int imageY;
private int imageWidth;
private int imageHeight;
/** Creates a new instance of ImageView */
public ImageView() {
addComponentListener(this);
}
public BufferedImage getImage() {
return image;
}
public Rectangle getImageBounds() {
if (image == null) {
return null;
} else {
return new Rectangle(imageX, imageY, imageWidth, imageHeight);
}
}
public void setImage(final BufferedImage newValue) {
image = newValue;
computeBounds();
repaint();
}
@Override
public void paint(Graphics g) {
long tm = System.currentTimeMillis();
if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
BufferedImage img = image;
if (img != null) {
g.drawImage(img, imageX, imageY, imageWidth, imageHeight, null);
}
tm = System.currentTimeMillis()-tm;
}
public void componentResized(ComponentEvent e) {
computeBounds();
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
computeBounds();
}
public void componentHidden(ComponentEvent e) {
}
private void computeBounds() {
BufferedImage img = image;
if (img != null) {
int width = this.getWidth();
int height = this.getHeight();
int wi = img.getWidth();
int hi = img.getHeight();
imageWidth = width;
imageHeight = height;
imageX = 0;
imageY = 0;
if (wi*height < hi*width) {
imageWidth = wi*height/hi;
imageX = (width-imageWidth)/2;
} else {
imageHeight = hi*width/wi;
imageY = (height-imageHeight)/2;
}
}
}
答案 1 :(得分:0)
您需要创建一个JFrame
来放置面板:
public static void main(String[] args) {
JFrame frame = new JFrame("title");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//all the other things for the jframe
JPanel panel = new MyPanel();
frame.add(panel);
frame.setVisible(true);
frame.repaint();
}