java JFrame 中的图像显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10827117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Image display in JFrame
提问by Ben Hagel
I'm just wondering why this 100x100 px .gif image isn't showing up on the screen. The image is in the same directory, so the program should have no problem finding it. Does anybody know how to solve this problem?
我只是想知道为什么这个 100x100 px .gif 图像没有显示在屏幕上。该图像在同一目录中,因此程序应该可以找到它。有谁知道如何解决这个问题?
import java.awt.*;
import java.awt.image.ImageObserver;
import java.io.File;
import javax.imageio.*;
import javax.swing.*;
public class Window extends JFrame{
//the pictures
ImageIcon guy = new ImageIcon("tester.gif");
JLabel pn = new JLabel(guy);
JPanel panel = new JPanel();
Window(){
super("Photuris Lucicrescens");
//Important
setSize(700,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setVisible(true);
//Decoration
Image customIcon = Toolkit.getDefaultToolkit().getImage("iconImage.gif");
setIconImage(customIcon);
//Adding the image
add(pn);
}
}
采纳答案by Yonutt
I try it on my computer and image is showing up on icon. If you want show the image on background try this :
我在我的电脑上试了一下,图像显示在图标上。如果你想在背景上显示图像,试试这个:
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.*;
public class Caine extends JFrame{
//the pictures
ImageIcon guy = new ImageIcon("tester.gif");
JLabel pn = new JLabel(guy);
JPanel panel = new JPanel();
Caine(){
super("Photuris Lucicrescens");
//Important
setSize(700,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setVisible(true);
JLabel im = new JLabel(new ImageIcon("iconImage.gif"));
setIconImage(customIcon);
panel.add(im);
add(pn);
}
}
回答by Guillaume Polet
The problem is that you add two components to the JFrame. When you add a Component to a JFrame, it actually adds it to its content pane. By default, the content pane uses the BorderLayout as its LayoutManager. If you don't set a constraint, the component is considered to be in the center. Therefore, here you have two components that are in the center and receives the same bounds from the LayoutManager, resulting in only one component to be shown, the other being hidden. This is why you see the JPanel and not the JLabel.
问题是您向 JFrame 添加了两个组件。当您将组件添加到 JFrame 时,它实际上是将它添加到其内容窗格中。默认情况下,内容窗格使用 BorderLayout 作为其 LayoutManager。如果不设置约束,则组件被视为位于中心。因此,这里有两个组件位于中心并从 LayoutManager 接收相同的边界,导致只有一个组件被显示,另一个被隐藏。这就是您看到 JPanel 而不是 JLabel 的原因。
If you want to see the JLabel, then don't add that panel to the frame.
如果您想查看 JLabel,请不要将该面板添加到框架中。
Other remarks:
其他备注:
- setVisible() should be invoked after you have created your component hierarchy.
- 在创建组件层次结构后,应调用 setVisible()。