2013-03-23 69 views
0

我剛開始製作一個簡單的MP3播放器,我正在創建播放,向前,後退等...按鈕,但出於某種原因只有第一個按鈕出現,並且使第二個按鈕出現,我必須去滾動它。如果你能幫我解決這個問題,那會很棒。我使用兩個圖像,一個名爲play.jpg,另一個名爲next.png。JButton不可見,直到我滾動它

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


public class Graphic extends JPanel{ 

JFrame f = new JFrame(); 
JPanel p = new JPanel(new GridBagLayout()); 

public Graphic(){ 

    gui(); 

} 

public void gui(){ 

    f.setVisible(true); 
    f.setSize(1600,900); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(p); 

    ppr(75,26,25,25,"pics/play.jpg"); 
    //above is the play button 


    ppr(40,26,25,25,"pics/next.png"); 
// above is the button that wont appear until it is scrolled over (it is just to the  left of the button above 



} 

public void ppr(int x, int y, int width, int height, String file){ 
    p.setLayout(null);  

    Toolkit tool = Toolkit.getDefaultToolkit(); 
     Image player = tool.getImage(file); 
      ImageIcon playbutton = new ImageIcon(player); 

    JButton play = new JButton(playbutton); 
     play.setBounds(x, y, width, height); 
      p.add(play); 

    // ********************** above is the the method that makes a button   


} 


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

} 



    } 
+0

要強調:*不要*做任何手動調整/定位組件 - 永遠 - 使用合適的LayoutManager – kleopatra 2013-03-23 11:20:10

回答

1

請勿使用setBounds。使用指定GridBagLayout 同時初始化面板,並指定GridBagConstraints

+0

你知道任何好的教程,我無法找到任何 – user2109242 2013-03-23 13:44:44

1

所有成分已被添加到GUI的setVisible(true)方法應該被調用。

我也同意更好的GUI設計的其他建議。

+0

我同意。過去的實驗讓我發現你的答案是正確的。出於某種原因,我的第一個傾向是對設計發表評論。此外,我不確定,也無法在當前機器上測試它,但我相信在美國東部時間運行也可以解決問題。 – KyleM 2013-03-23 05:37:12

+0

@KyleM,當你添加組件到一個可見的GUI時,你需要重新驗證()面板。否則面板的大小是(0,0),所以Swing認爲沒有東西可以畫。 – camickr 2013-03-23 05:54:24

+0

啊,是的,再次糾正。它回到我身邊......慢慢地。 – KyleM 2013-03-23 06:11:57