2012-09-04 58 views
0

我想用單選按鈕製作一個簡單的GUI,並將它們分組到一個面板中。我希望它位於最左側,所以我使用了setBounds方法。無論我在參數上輸入什麼數字,該面板都不會移動。面板是否不受setBounds方法的影響?或者有另一種方式來定位我的面板。這裏是我的代碼片段:爲什麼我的面板在設置邊界後仍然沒有正確定位?

JPanel radioPanel = new JPanel(); 
    radioPanel.setLayout(new GridLayout(3,1)); 
    JRadioButton Rbutton1 = new JRadioButton("Credit Card"); 
    JRadioButton Rbutton2 = new JRadioButton("E-Funds"); 
    JRadioButton Rbutton3 = new JRadioButton("Check"); 
    Rbutton3.setSelected(true); 
    ButtonGroup Bgroup = new ButtonGroup(); 
    Bgroup.add(Rbutton1); 
    Bgroup.add(Rbutton2); 
    Bgroup.add(Rbutton3); 
    radioPanel.add(Rbutton1); 
    radioPanel.add(Rbutton2); 
    radioPanel.add(Rbutton3); 
    radioPanel.setBounds(10,50,50,40); //this is where I'm trying to position the panel with the radio buttons 
    paymentPanel.add(radioPanel); 
    contentPane.add(paymentPanel); //contentPane is the frame 
    contentPane.setVisible(true); 
+0

對不起,我在這裏有點新。我剛剛學會了這個「接受」的事情,但我現在做了一些事情。 :D – nutellafella

+0

您遇到的問題是'paymentPanel'正在使用覆蓋您的設置的'LayouManager'。儘管你可能會想,但這是一件好事。 – MadProgrammer

回答

2

設置框架的佈局。例如:

contentPane.setLayout(new BorderLayout()); 
    contentPane.add(paymentPanel, BorderLayout.LINE_START); 

更多關於佈局管理器的信息,你可以在這裏找到:A Visual Guide to Layout Managers

+0

謝謝!有效。 :) – nutellafella

+0

第二個想法,有一個小問題。當我使用您提供的代碼時,我的付款面板突然調整到我的無線面板的寬度。我試着做這個'paymentPanel.add(radioPanel,BorderLayout.LINE_START);'但它不起作用。 – nutellafella

+0

查看上面的鏈接(「佈局管理器視覺指南」)並閱讀有關選定的佈局。 – rebeliagamer

0

您可以爲您的contentPane佈局設置爲空佈局。

contentPane.setLayout(null); 

然後你的setBounds()將工作完全按照你的設計。

注:

創建具有絕對定位的容器容器是否含有大小容器上的窗口可能會出現問題。

+0

我可以做到這一點,但我的教授指示我們使用BorderLayout作爲contentPane。 – nutellafella

相關問題