gpt4 book ai didi

java - 显示一个 ImageIcon

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:52:33 25 4
gpt4 key购买 nike

我正在尝试在 JPanel 上显示图像。我正在使用 ImageIcon 来呈现图像,图像与类文件位于同一目录中。但是,没有显示图像,也没有发生错误。任何人都可以协助解决我的代码有什么问题......

package ev;

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Image extends JPanel {

ImageIcon image = new ImageIcon("peanut.jpg");
int x = 10;
int y = 10;

public void paintComponent(Graphics g) {
super.paintComponent(g);
image.paintIcon(this, g, x, y);
}
}

最佳答案

这是程序员之间常见的困惑。这getClass().getResource(path) 从类路径加载资源。

ImageIcon image = new ImageIcon("peanut.jpg");

如果我们只提供图像文件的名称,那么 Java 就是在当前工作目录中寻找它。如果您使用的是 NetBeans,则 CWD 是项目目录。你可以通过以下调用在运行时找出 CWD:

System.out.println(new File("").getAbsolutePath());

以下是代码示例,您可以自行测试。

package com.zetcode;

import java.awt.Dimension;
import java.awt.Graphics;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawingPanel extends JPanel {

private ImageIcon icon;

public DrawingPanel() {

loadImage();
int w = icon.getIconWidth();
int h = icon.getIconHeight();
setPreferredSize(new Dimension(w, h));

}

private void loadImage() {

icon = new ImageIcon("book.jpg");
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

icon.paintIcon(this, g, 0, 0);
}

}

public class ImageIconExample extends JFrame {

public ImageIconExample() {

initUI();
}

private void initUI() {

DrawingPanel dpnl = new DrawingPanel();
add(dpnl);

// System.out.println(new File("").getAbsolutePath());

pack();
setTitle("Image");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
JFrame ex = new ImageIconExample();
ex.setVisible(true);
}
});
}
}


下图是放书的地方.jpg如果我们只提供图像名称,NetBeans 中的图像到 ImageIcon 构造函数。

Location of the image in NetBeans project

我们在命令行中有相同的程序。我们在 ImageIconExample 里面目录。

$ pwd/home/vronskij/prog/swing/ImageIconExample$ tree.├── book.jpg└── com    └── zetcode        ├── DrawingPanel.class        ├── ImageIconExample$1.class        ├── ImageIconExample.class        └── ImageIconExample.java2 directories, 5 files

程序使用以下命令运行:

$ ~/bin/jdk1.7.0_45/bin/java com.zetcode.ImageIconExample

您可以在我的 Displaying image in Java 中找到更多信息教程。

关于java - 显示一个 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10084787/

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