【发布时间】:2014-01-19 21:31:39
【问题描述】:
import javax.swing.*;
import java.awt.*;
public class Main
{
public static void main(String[] args)
{
//load the card image from the gif file.
final ImageIcon cardIcon = new ImageIcon("cardimages/tenClubs.gif");
//create a panel displaying the card image
JPanel panel = new JPanel()
{
//paintComponent is called automatically by the JRE whenever
//the panel needs to be drawn or redrawn
public void paintComponent(Graphics g) {
super.paintComponent(g);
cardIcon.paintIcon(this, g, 20, 20);
}
};
//create & make visible a JFrame to contain the panel
JFrame window = new JFrame("Title goes here");
window.add(panel);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBackground(new Color(100, 200, 102));
window.setPreferredSize(new Dimension(200,200));
window.pack();
window.setVisible(true);
}
}
我正在尝试制作一个在窗口上显示所有 52 张卡片的 java 项目。我的窗口可以工作,但我无法让卡片出现在窗口上。
我在 OSX 上使用 eclipse,在项目 src 文件中我有一个(默认包)容器,里面有我的 Main.java 文件。然后我将我的 cardimages 文件夹放在同一个 src 文件中。
如何让图像显示在窗口中?
【问题讨论】:
-
你测试过ImageIcon,cardIcon,是否为空吗?如果是这样,您可能在错误的位置寻找图像。我自己,我使用
ImageIO.read(...)将我的图像作为 BufferedImages 获取,并且不传入文件,而是从 Class 方法getResource(...)获取的 URL。 -
测试正常,可能图片路径不对。
-
原始海报,您应该显示您的 cardImages 文件夹相对于您的类文件的位置。
-
为什么你在paintComponent中的paintIcon可以工作但是......
-
只需将您的课程移动到有效的包中即可。您的代码可以正常工作。
标签: java swing icons paintcomponent