2016-08-25 152 views
0

我试图将图像“Pic.png”添加到此JLabel“label1”并将其显示在JFrame“window1”上的JPanel“panel1”上。但是当它运行时它不显示我的图像。任何人帮助? (我读过关于将其添加到源文件或其他内容,但我不确定我在做什么,因为我是Java新手,如果没有源代码中的图像,是否无法访问图片?)试图将图像添加到标签但不起作用?

public class UIForIshidaQuery { 

    public static void main(String[] args) { 
     System.out.println("Running..."); 

     JFrame window1 = new JFrame(); 
     window1.setVisible(true); 
     window1.setSize(1080, 720); 
     window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel1 = (JPanel) window1.getContentPane(); 
     JLabel label1 = new JLabel(); 
     panel1.setLayout(null); 
     ImageIcon image = new ImageIcon("C:\\Users\\BC03\\Pictures\\Saved Pictures\\Other\\Pic.png"); 
     label1.setIcon(image); 
     label1.setBounds(500, 500, 500, 500); 
     panel1.add(label1); 
    } 
} 
+0

是否有'new File(“C:\\ Users \\ BC03 \\ Pictures \\ Saved Pictures \\ Other \\ Pic.png”)。exists()'return true? – Berger

+0

查看[tag:embedded-resource]标签中引用的示例[here](http://stackoverflow.com/tags/embedded-resource/info)。 – trashgod

+0

是的,它返回true @Berger – Cutter

回答

2

窗口应作为最后的呼叫设置可见。请勿使用null布局。这工作。

import java.net.*; 
import javax.swing.*; 

public class UIForIshidaQuery { 

    public static String url = "http://i.stack.imgur.com/gJmeJ.png"; 

    public static void main(String[] args) throws MalformedURLException { 
     System.out.println("Running..."); 

     JFrame window1 = new JFrame(); 
     window1.setSize(1080, 720); 
     window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel1 = (JPanel) window1.getContentPane(); 
     JLabel label1 = new JLabel(); 
     //panel1.setLayout(null); 
     ImageIcon image = new ImageIcon(new URL(url)); 
     label1.setIcon(image); 
     //label1.setBounds(500, 500, 500, 500); 
     panel1.add(label1); 
     window1.setVisible(true); 
    } 
} 
  1. Java的图形用户界面有不同的OS”,屏幕大小,屏幕分辨率等方面的工作在不同的地区使用不同的PLAFs。因此,它们不利于像素的完美布局。请使用布局管理器,或combinations of them以及white space的布局填充和边框。
+0

谢谢,这个作品! – Cutter

+0

以上信息是正确的,像素完美的布局很难在Java Swing中实现。因此,为了检查现有代码中的图像,您可以运行并尝试最大化/最小化窗口,并且您会看到图像出现,而您在运行代码时不会立即出现图像。 –

1

如果您正在使用的IntelliJ IDEA:

  1. 右键点击你的项目的根目录,并选择New>目录;
  2. 例如调用新的目录'资源';
  3. 右键单击新建的目录并选择标记目录为>资源根目录;
  4. 在目录中添加您的图像文件;
  5. 访问您的文件中正确: CurrentClass.class.getClassLoader().getResource("pic.png").getFile();

的ImageIcon的可以这样初始化:

File file = new File(CurrentClass.class.getClassLoader().getResource("pic.png").getFile()); 
     BufferedImage image = null; 
     try { 
      image = ImageIO.read(file); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     ImageIcon imageIcon = new ImageIcon(image); 
+0

我没有使用IntelliJ IDEA。 – Cutter

+0

对不起,我错过了你添加的netbeans标签。对于使用IntelliJ IDEA的其他用户来说仍然是一个很好的参考。 – Thibstars