2014-02-13 35 views
1

我曾尝试过无数种将jpg图像添加到Jframe中但未成功的方法,代码将编译但图像不会出现。图像存储在项目的源文件中!谢谢您的帮助。如何从源文件夹添加图像并将其映像到JFrame中?

public class GordonsWindow extends JFrame { 
    public GordonsWindow() { 
     JMenuBar menuBar = new JMenuBar(); 
     JMenu menuFile = new JMenu(); 
     JMenu menuStores = new JMenu(); 
     JMenuItem menuFileExit = new JMenuItem(); 

     JMenuItem menuStoresArmagh = new JMenuItem(); 

     JPanel paneStores = new JPanel(new FlowLayout()); 
     paneStores = new JPanel(); 
     paneStores.setPreferredSize(new Dimension(500,300)); 
     paneStores.setBackground(Color.blue); 
     JButton ArmaghButton = new JButton(); 
     ImageIcon icon = new ImageIcon("Gordons.jpg"); 
     JLabel label = new JLabel(); 
     label.setIcon(icon);   

     ArmaghButton.setText("Armagh"); 

     paneStores.add(ArmaghButton); 
     paneStores.add(label); 

     add(paneStores); 

     menuFile.setText("File"); 
     menuFileExit.setText("Exit"); 

     menuStores.setText("Stores"); 
     menuStoresArmagh.setText("Armagh"); 

     ArmaghButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       Armagh.windowActivated(); 
      } 
     }); 

     menuFileExit.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       GordonsWindow.this.windowClosed(); 
      } 
     }); 

     menuFile.add(menuFileExit); 
     menuBar.add(menuFile); 

     menuBar.add(menuStores); 
     menuStores.add(menuStoresArmagh); 

     setTitle("Gordons Chemists Application"); 
     setJMenuBar(menuBar); 
     setSize(new Dimension(800, 800)); 

     //Add Window Listener 
     this.addWindowListener(new WindowAdapter() { 
      public void windowClosing(WindowEvent e) { 
       GordonsWindow.this.windowClosed(); 
      } 
     }); 
    } 

    protected void windowClosed() { 
     System.exit(0); 
    } 
} 
+0

http://stackoverflow.com/questions/13428796/adding-background-pic-to-jframe 你可能想看看那个 – Mozzie

+0

也许资源加载问题?现在,图像需要与GordonsWindow位于相同的包或文件夹中,或者直接放在类路径中的文件夹中... – Rob

回答

2

你想通过你的类路径加载它。只要

ImageIcon icon = new ImageIcon(GordonsWindow.class.getResource("/images/Gordons.jpg"); 

images直接坐落在src

ProjectRoot 
     src 
      images 
       Gordons.jpg 
0

遗憾;错过了label.seticon()这个例子不需要的其他代码使我困惑。

下一次使用SSCCE

,然后你需要绘制它以某种方式在组件上;

方法我用的是:

JPanel imageholder=new JPanel() 
     { 
      protected void paintComponent(Graphics g) 
      { 
       super.paintComponent(g) 
       g.drawImage(ImageVariable,0,0); 
      } 
     }; 
     j.setBounds(<insert size here>); 
相关问题