2015-04-14 82 views
1

這是我正在使用的Yahtzee遊戲的一部分。我試圖將背景設置爲項目文件夾中的yahtzee.png文件。 我評論了我的嘗試,因爲它不適合我。有沒有更好的方法來設置它?帶JFrame的背景圖片

 ExFrame(int numPlayers) 
    { 
     frame = new JFrame(); 
     frame.setSize(450+150*numPlayers,700); 

     frame.setTitle("YAHTZEE!"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     this.numPlayers = numPlayers; 
     this.numGridRows = 20; 
     this.buttonWidth = 140; 
     this.numCreateButLabCalls = 0; 
     this.component = new DiceComponent(buttonWidth*2); 
     this.cButtons = new JButton[numGridRows]; 
     this.cButtonsText = new String[numGridRows]; 
     this.cLabels = new JLabel[numPlayers][numGridRows]; 
     this.statusLabel = new JLabel("<html>New game has been started!<br>Please select the dice that you wish to hold or click on a scoring button</html>"); 
     this.score = new YahtzeeScore[numPlayers]; 

     //populate score array 
     for(int k = 0; k < numPlayers; k++) 
     { 
      score[k] = new YahtzeeScore(cButtons,cLabels, statusLabel, component.getDieArray(), cButtonsText, numGridRows, k); 
     } 

     statusLabel.setPreferredSize(new Dimension(buttonWidth*2, 100)); 
     centerPanel = new JPanel(new GridLayout(numGridRows,numPlayers+1)); //columns based on numPlayers 

     component.rollDice(true); 
     popCenterPanel(); 
     for(int k = 0; k < numPlayers; k++) 
      score[k].reset(); 
     addListeners(); 

     frame.setLayout(null); 
     frame.add(component); 
     frame.add(statusLabel); 
     frame.add(centerPanel); 
    // frame.add(new JLabel(new ImageIcon("/YahtzeeAgain/yahtzee.png"))); 
     Insets insets = frame.getInsets(); 
     Dimension size = statusLabel.getPreferredSize(); 
     statusLabel.setBounds(100+ insets.left,insets.top,size.width,size.height); 
     size = component.getPreferredSize(); 
     component.setBounds(insets.left, 150 + insets.top, 
       size.width, size.height); 
     size = centerPanel.getPreferredSize(); 
     centerPanel.setBounds(290 + insets.left, 140 + insets.top, 
       size.width, size.height); 
    centerPanel.setBackground(Color.gray); 
    frame.add(this); 
    frame.setVisible(true); 


    } 
+0

你可以檢查絕對路徑並分享結果嗎? – marmeladze

+0

如果可以,請避免使用JLabel作爲背景組件,但不會基於其子組件計算其首選大小,而是根據圖標和文本屬性計算其首選大小。相反,創建一個自定義組件並覆蓋它的paintComponent方法,[示例](http://stackoverflow.com/questions/24176008/background-image-for-a-jpanel-not-working/24176183#24176183),而一點點更復雜,更靈活 – MadProgrammer

回答

2

最好的辦法:

添加你的背景JLabel放在框架的contentPane的(因爲你正在做的),然後做的setLayout(NULL)就可以了,並添加所有其他組件到您的背景JLabel

+0

謝謝。這工作。我猜那裏的訂單是讓我感到滿意的。 –

+0

請注意,JLabel不會根據子組件的需要計算其首選大小,但會使用標籤的圖標和文本屬性,這可能會在不同平臺上呈現問題。 – MadProgrammer

0

如何

frame.setContentPane(new JLabel(new ImageIcon("/YahtzeeAgain/yahtzee.png"))); 
+0

當我這樣做時,它將整個屏幕設置爲灰色,似乎掩蓋了所有其他JPanel。有趣... –