2014-02-13 33 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>); 
相關問題