2013-07-14 71 views
0

您好,感謝您提供任何響應。我是初學Java編程人員,並決定使用幾個按鈕創建一個基本的J Frame。我一直在努力解決這個問題,在我繼續下一步之前,什麼時候解決這個問題。下面我寫了一個J Frame的一些代碼,我將兩個按鈕都放在了我想要的位置,但是當我添加第二個按鈕時,它會覆蓋第一個按鈕。我想知道我是否以正確的方式接近這一點,以及如何改進它。您好需要幫助在JFrame中放置第二個JButton

Frame guiWindow = new Frame(); 
    JPanel pnlButton = new JPanel(); 
    JButton btnAdd = new JButton("A"); 
    JPanel pnlButton2 = new JPanel(); 
    JButton btnAdd2 = new JButton("B"); 

    public Frame1() {  

     //Button 1 
     pnlButton.setLayout(null); 
     btnAdd.setBounds(40, 300, 100, 50); 
     pnlButton.setBounds(40, 300, 50, 50); 
     pnlButton.add(btnAdd); 
     add(pnlButton);   

     //Button2   
     pnlButton2.setLayout(null); 
     btnAdd2.setBounds(260, 300, 100, 50); 
     pnlButton2.setBounds(260, 300, 100, 50); 
     pnlButton2.add(btnAdd2); 
     add(pnlButton2); 
     setSize(400, 400); 
     setTitle("Pratice"); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setVisible(true); 
    } 
} 

回答

0

好吧,你是新的,這是可以理解的,爲什麼發生這種情況。首先要知道的是,當您將JPanel添加到JFrame中時;除非你正在做某種定位或需要的東西,否則你只能添加一個JPanel。這可能是它重疊的原因。您正在嘗試添加一件東西,然後再添加一件在同一地區。所有你需要做的就是把pnlButton2取出來,並使用pnlButton作爲添加按鈕的主要方法:)你也可以使用一個名爲GridLayout的佈局管理器。這可能是非常令人困惑的事情,但我可以解釋:

GridLayout是一種在JFrame或任何類型的框架上創建網格效果的方法。它會將您的按鈕對齊到所選大小的網格中。

這裏是一個鏈接,以幫助更多的解釋:GridLayout - Oracle Java Helper

但這裏是一些代碼來解釋我在談論的JPanels和東西:)

希望我幫助你,並沒有迷惑你

Frame guiWindow = new Frame(); 
JPanel pnlButton = new JPanel(); 
JButton btnAdd = new JButton("A"); 
//JPanel pnlButton2 = new JPanel(); not needed :) 
JButton btnAdd2 = new JButton("B"); 

public Frame1() { 


//Button 1 

pnlButton.setLayout(null); 
btnAdd.setBounds(40, 300, 100, 50); 
pnlButton.setBounds(40, 300, 50, 50); 
pnlButton.add(btnAdd); 
pnlButton.add(btnAdd2); // see how we add the second button? 
add(pnlButton); 

/* remove this section 
//Button2   
pnlButton2.setLayout(null); 
btnAdd2.setBounds(260, 300, 100, 50); 
pnlButton2.setBounds(260, 300, 100, 50); 
pnlButton2.add(btnAdd2); 
add(pnlButton2); 
*/ 




setSize(400, 400); 
setTitle("Pratice"); 
setLocationRelativeTo(null); 
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
setVisible(true); 
}