这是我的代码,显然有两个问题:
package test;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Component;
public class something {
public static void main(String[] args) {
ImageIcon icon = new ImageIcon("src/icon.png",("What a great image"));
JPanel window = new JPanel();
window.setLocation(100,100);
window.setSize(300, 500);
window.setVisible(true);
}
所以我不知道为什么 JPanel 不会显示出来,我导入的图像正确吗?我已经创建了图标并将其放置在 SRC 文件夹中。如果我没有正确导入它,那么我该如何导入呢?这个问题也适用于 Graphics Swing,因为我有兴趣尽快了解它。
最佳答案
So I don't know why the JPanel won't reveal itself
您还没有将其添加到任何可以显示的内容中。 JPanel
只是一个普通容器,允许您向其添加其他组件。
您需要某种Window
来实际显示此容器,例如......
JPanel window = new JPanel();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(window);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
通读一下How to Make Frames (Main Windows)了解更多详情
I've already created the icon and placed it in the SRC folder. If I'm not importing it right, how do I import it then?
这是一个复杂的问题,因为您已将图像添加到 src
目录中,它会更改图像加载方式的上下文。本质上,它成为一种嵌入式资源。
所以不要使用...
ImageIcon icon = new ImageIcon("src/icon.png",("What a great image"));
您需要使用更像...的东西
ImageIcon icon = new ImageIcon(something.getClass().getResource("icon.png"),("What a great image"));
相反
您可能会发现阅读How to Use Labels , Creating a GUI With JFC/Swing , Initial Threads , Laying Out Components Within a Container , Reading/Loading an Image有帮助
关于java - 如何使用 ImageIcon 导入图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23945251/