2011-12-08 145 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