2013-03-23 68 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