2011-12-08 144 views
-1

我似乎無法弄清楚這一點。
請幫助我需要這個來解決我的項目。
呀我要補充這讓我張貼JLabel作爲背景圖片

import javax.swing.*; 
import java.awt.*; 

@SuppressWarnings("serial") 
public class MainFrame extends JFrame { 


public static void Draw(){ 
    DrawFrame(); 
} 


public static void DrawFrame(){ 
    int h = 600; 
    int w = 340; 
    JFrame frame = new JFrame(); 
    JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png")); 


    frame.setResizable(false); 
    frame.setSize(h, w); 
    frame.setTitle("MarioCraft"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    frame.add(background1); 

    background1.setVisible(true); 
    background1.setIcon(new ImageIcon("/res/mariocraft_main.png")); 
    background1.setText("Background failed to load"); 

    } 

} 
+0

-1什麼是你的問題的樣本代碼片段?而不是添加無意義的文本,也許你應該嘗試解釋你想做什麼更徹底 – PTBG

+0

我的意思是我嘗試使用JLabel作爲背景。問題在標題 – Alek345

+0

你在問什麼?你的代碼有什麼問題?請不要將代碼轉儲到問題中,然後說:「修復它」,解釋你想說的話。 –

回答

3

JLabel總是以實際尺寸顯示圖像,因此您不應該手動設置框架的尺寸。

相反的代碼應該是這樣的:

JLabel background1 = new JLabel(new ImageIcon("/res/mariocraft_main.png")); 

JFrame frame = new JFrame();  
frame.add(background1); 
frame.pack(); 
frame.setResizable(false);  
frame.setVisible(true);  
1

您需要的JLabel實例添加到你意識到它的JFrame之前(即使其可見)。此外,刪除這三個電話:

background1.setVisible(true); 
background1.setIcon(new ImageIcon("/res/mariocraft_main.png")); 
background1.setText("Background failed to load"); 

他們是完全沒有必要的。此外,將背景圖像設置爲組件的另一種方法是覆蓋該方法,並將該圖像直接繪製到該對象的Graphics對象上。

+0

你可以做一個paintComponent檢查嗎? – Alek345

0

你想設置JLabel作爲JFrame背景圖像。然後,

frame.setContentPane(new JLabel(new ImageIcon("someimage.jpg")); 

見採取here

frame.setLayout(new BorderLayout()); 
frame.setContentPane(new JLabel(new ImageIcon("someimage.jpg"))); 
frame.setLayout(new FlowLayout()); 
l1=new JLabel("Here is a button"); 
b1=new JButton("I am a button"); 
frame.add(l1); 
frame.add(b1); 
0
import java.awt.Container; 
import java.awt.FlowLayout; 


import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 


public class Mainframe extends JFrame 
{ 
    public JLabel image ; 



    public Container c; 

    public Mainframe() 
    { 
     c=this.getContentPane(); 
     image=new JLabel(new ImageIcon("bg.jpg")); 
     image.setSize(500, 550); 

     c.setLayout(new FlowLayout()); 
     c.add(image); 

     add(image); 




     this.setSize(500, 550); 
     this.show(); 
     this.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) 
    { 
      new Mainframe(); 
    } 

} 
+0

這裏的圖像將被放置在中心。我可以將圖像設置爲整個幀 – gangu