简体   繁体   English

.png图标未加载到JFrame窗口中

[英].png icon not loading in a JFrame window

一个简单的png图像

import java.awt.*;
import javax.swing.*;

public class Program {
public static JButton button;
public static void main(String args[]){
    JFrame win=new JFrame("title");
    win.setVisible(true);
    win.setSize(500,500);
    win.setLayout(new FlowLayout());
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ImageIcon i=new ImageIcon("icon.png");
    button=new JButton("hello",i);
    win.add(button);
    button.setToolTipText("click me");

}
}

When I run the file , I just get the text "hello" on the button but no image. 运行文件时,我只是在按钮上看到文本“ hello”,但没有图像。
(This image was downloaded from http://icons.iconarchive.com/icons/iynque/flat-ios7-style-documents/512/png-icon.png ) (此图像从http://icons.iconarchive.com/icons/iynque/flat-ios7-style-documents/512/png-icon.png下载)

The image is stored in the project src file. 图像存储在项目src文件中。

Image shouldn't be in src but in main application directory, usually level above. 映像不应位于src而应位于主应用程序目录中,通常位于更高级别。 So move your icon or change code to: 因此,将图标移动或将代码更改为:

ImageIcon i=new ImageIcon("src/icon.png");

You should consider adding it to your resources (so it will be placed in jar) and opening via getResource() . 您应该考虑将其添加到资源中(以便将其放置在jar中)并通过getResource()打开。 Next problem in example is that it won't be displayed until window is refreshed by resize or other action. 示例中的下一个问题是,直到通过调整大小或其他操作刷新窗口后,它才会显示。 Add this line at the end: 在末尾添加以下行:

win.pack();

Or other method that will refresh window content. 或其他将刷新窗口内容的方法。

试试这个:ImageIcon i = new ImageIcon(“ src / icon.png”);

getClass().getResource("icon.png")

如果您的图像文件位于Program.java的同一目录下,并且在编译时确实将其打包到与Program.class相同的目录下,则将执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM