2015-06-01 20 views
0

我在將圖像設置爲背景時遇到了一些問題。只有當我移動整個窗口時,圖像纔會顯示。下面是我的代碼片段,包括設置背景圖片。Java JFrame背景無法正常工作。僅在移動實際窗口時才起作用

playButton = new JButton(pbI); 
instructionButton = new JButton(ibI); 
quitButton = new JButton(qbI); 

mainFrame = new JFrame("My Major Project"); 
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
mainFrame.setSize(800, 600); 
mainFrame.setLocationRelativeTo(null); 
mainFrame.setLayout(null); 

mainFrame.setLayout(new BorderLayout()); 
mainFrame.setContentPane(new JLabel(new ImageIcon("background.gif"))); 
mainFrame.setLayout(new FlowLayout()); 

mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
+0

請忽略第一對幾行代碼,因爲它們是圖像按鈕 – boy

+0

避免使用'ImageIcon',它可能有問題,請考慮使用'ImageIO'代替。爲此目的使用'JLabel'並不是世界上最好的想法,因爲'JLabel'只會從圖標和文本屬性計算出它的首選大小,這意味着它可能會裁剪它的內容。你可能會考慮使用類似[this](http://stackoverflow.com/questions/13791984/add-an-background-image-to-a-panel/13792503#13792503),它可以讓你控制'首選尺寸「的面板計算 – MadProgrammer

+0

好吧謝謝生病嘗試 – boy

回答

0

爲了更新JFrame,您需要致電mainFrame.repaint();

+0

重畫框架可能不會影響內容 – MadProgrammer

+0

我已經做了,只是我沒有包括它 – boy