[英]Image not showing in JFrame
Why is my image not being displayed? 为什么我的图像没有显示? The buttons are always there, but the image does just not appear.
按钮始终在那里,但是图像不会出现。 It may not be a programming problem.
这可能不是编程问题。 Where should I place the image?
我应该在哪里放置图片?
First Class File: 头等舱文件:
public class start {
public static void main(String args[]){
menu m1 = new menu();
m1.setVisible(true);
}
}
Second Class File: 二级文件:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class menu extends JFrame{
private static final long serialVersionUID = 1L;
public menu(){
super("Parachute!");
setSize(1000, 800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel main = new JPanel(new GridBagLayout());
JPanel title = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
JButton play = new JButton("Play!");
JButton help = new JButton("Help");
JButton options = new JButton("Options");
ImageIcon logo = new ImageIcon("parachute.jpg");
JLabel imageLogo = new JLabel(logo);
gbc.gridx = 0;
gbc.gridy = 0;
main.add(play, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
main.add(help, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
main.add(options, gbc);
title.add(imageLogo);
add(title, BorderLayout.NORTH);
add(main, BorderLayout.CENTER);
}
}
Two things: 两件事情:
First, you are not setting the layout to be borderlayout before using it. 首先,在使用布局之前,不要将布局设置为borderlayout。 Do:
做:
setLayout(new BorderLayout())
Second, to check if the parachute.jpg file is present, you can check like this: 其次,要检查parachute.jpg文件是否存在,您可以像这样检查:
File f = new File("parachute.jpg");
System.out.println(f.exists());
If this prints false
, it means it could not find the file. 如果显示
false
,则表示找不到文件。 In that case , you need to put the image file in correct directory. 在这种情况下,您需要将图像文件放在正确的目录中。
I believe you are using an IDE like Netbeans or Eclipse. 我相信您正在使用NetBeans或Eclipse之类的IDE。 In that case, put the image in the root directory for the project.
在这种情况下,请将图像放在项目的根目录中。 For example, you have a project
Test
. 例如,您有一个项目
Test
。 Then the image file should be in the Test folder. 然后,图像文件应位于“测试”文件夹中。 The IDE's generally look for files from the root of the project.
IDE通常从项目的根目录中查找文件。
PS : As you are new to programming, you should try to follow the conventions of the language you are using. PS :刚接触编程时,应尝试遵循所用语言的约定。 It makes it easy for others to understand your code.
它使其他人容易理解您的代码。 Look here for Java conventions.
在这里查找Java约定。
Have you tried to add main to content? 您是否尝试将main添加到内容? Something like this:
getcontent().add(main, BorderLayout.CENTER)
像这样的东西:
getcontent().add(main, BorderLayout.CENTER)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.