2013-04-16 225 views
1

我該如何擺脫那個灰色框?設置背景圖片

這就是我說的:

我真的很感激,如果你能幫助我

全部代碼在這裏:http://pastebin.com/nrpCTjvV

public final void initUI() { 

    JPanel panel = new JPanel(); 
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 

    panel.setBorder(new EmptyBorder(new Insets(90, 155, 40, 60))); 

    JButton NewGame = new JButton ("New Game!"); 
    JButton Highscore = new JButton("Highscore"); 
    JButton Credits = new JButton ("Credits"); 
    JButton Website = new JButton ("Website"); 
    JButton Exit = new JButton  ("Exit"); 

    panel.add(NewGame); 
    panel.add(Box.createRigidArea(new Dimension(0, 5))); 
    panel.add(Highscore); 
    panel.add(Box.createRigidArea(new Dimension(0, 5))); 
    panel.add(Credits); 
    panel.add(Box.createRigidArea(new Dimension(0, 5))); 
    panel.add(Website); 
    panel.add(Box.createRigidArea(new Dimension(0, 5))); 
    panel.add(Exit); 

    final ButtonGroup entreeGroup = new ButtonGroup(); 
    JRadioButton radioButton; 
    panel.add(radioButton = new JRadioButton("Music1")); 
    radioButton.setActionCommand("Music1"); 
    entreeGroup.add(radioButton); 
    panel.add(radioButton = new JRadioButton("Music2")); 
    radioButton.setActionCommand("Music2"); 
    entreeGroup.add(radioButton); 
    panel.add(radioButton = new JRadioButton("No Music", true)); 
    radioButton.setActionCommand("No Music"); 
    entreeGroup.add(radioButton); 

    add(panel); 
    pack(); 

    setTitle("Title"); 
    JLabel background = new JLabel(new ImageIcon("background.png")); 
add(background); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLocationRelativeTo(null); 
    setResizable(false); 
    setSize(400, 400); 

} 
+0

panel.setOpaque(false);可能的複製:http://stackoverflow.com/questions/54926/make-a-jpanel-not-draw-its-background-transparent – Aboutblank

+0

它現在的作品!非常感謝! – user2287319

+0

@ user2287319,不,這不是使面板不透明的正確解決方案。 Swing不是設計爲在BorderLayout上的一個位置顯示兩個組件。您的解決方案恰巧因爲黑客而工作。這不是學習編程的好方法。例如,在添加所有組件之前,不應在框架上執行pack()。刪除該行代碼,看看會發生什麼。 – camickr

回答

3
add(panel); 
pack(); 
setTitle("Title"); 
JLabel background = new JLabel(new ImageIcon("background.png")); 
add(background); 

JFrame的默認佈局管理器是Bor derLayout。當你添加一個沒有指定約束的組件時,該組件被添加到CENTER中。您無法將多個組件添加到單個位置。

相反,您需要使用不同的組件作爲背景。然後,將面板添加到此組件。退房Background Panel。然後代碼會是這樣的:

Background background = new BackgroundPanel(...); 
background.add(panel); 
add(background); 
setResizable(false); 
pack(); 
...