2014-11-03 86 views
0

我無法將此JPanel添加到窗格的中心塊中。實質上,這個主窗口是一個BorderLayout,它的中心是centerPanel,西區塊和東區塊將是獨立的BorderLayouts。我搜索了這個問題,並查看了來自我的教授的示例代碼,並在這裏查看了stackoverflow,但在代碼中找不到問題。將JPanel添加到JApplet的BorderLayout中

我在Eclipse中完成所有的編碼,所以我使用了集成的AppletViewer。唯一出現的是一個空的灰色框,我期望看到包含JLabels和JTextAreas的centerPanel。

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

public class Lab7 extends JApplet implements ItemListener, ActionListener{ 

//variables 
private JLabel currentOrder, total; 
private JTextArea descTop, currentOrderTA, totalTA; 
private JRadioButton sizeSmall, sizeMedium, sizeLarge, typeDeep, typePan, typeHand; 
private JCheckBox pepperoni, bacon, extra_cheese, mushroom, pepper, sausage, tomato, olive; 
private JButton orderButton, resetButton; 
private ButtonGroup sizeBG, typeBG; 
private BorderLayout borderLayoutMain, borderLayoutWest, borderLayoutEast; 
private JPanel westPanel, centerPanel, eastPanel; 

public void init(){  
    Container pane = getContentPane(); 
    pane.setLayout(borderLayoutMain); 

    //borderLayoutMain centerPanel 
    centerPanel = new JPanel(); 
    centerPanel.setLayout(null); 

    currentOrder.setSize(200, 25); 
    currentOrder.setLocation(100, 25); 
    currentOrderTA.setSize(600, 400); 
    currentOrderTA.setLocation(100, 50); 
    currentOrderTA.setEditable(false); 
    total.setSize(200, 25); 
    totalTA.setLocation(100, 450); 
    totalTA.setEditable(false); 
    orderButton.setSize(100, 50); 
    orderButton.setLocation(100, 500); 
    resetButton.setSize(100, 50); 
    resetButton.setLocation(400, 500); 

    centerPanel.add(currentOrder); 
    centerPanel.add(currentOrderTA); 
    centerPanel.add(total); 
    centerPanel.add(totalTA); 
    centerPanel.add(orderButton); 
    centerPanel.add(resetButton); 

    pane.add(centerPanel, BorderLayout.CENTER); 
} 

回答

0

既然你已經爲容器的首選大小值由它確定免掉佈局管理器(centerPanel.setLayout(null);)的BorderLayout不再有任何想法的面板的大小應該是什麼(佈局管理器)

考慮在centerPanel上使用佈局管理器,請參閱Laying Out Components Within a Container以獲取更多詳細信息。

避免使用null佈局,像素完美的佈局是現代UI設計中的幻想。影響組件的個體大小的因素太多,其中沒有一個可以控制。搖擺設計爲核心與佈局管理工作,丟棄這些會導致沒有問題,問題是,你將花費更多的時間,試圖糾正

更多細節

更新見Why is it frowned upon to use a null layout in SWING?結束。 ..

當你調用

pane.setLayout(borderLayoutMain); 

borderLayoutMainnull,所以你現在有一個null頂層容器的佈局。

嘗試使用...

pane.setLayout(new BorderLayout()); 

,而不是...

+0

我已經改變了佈局線: centerPanel.setLayout(新的GridLayout(5,3)); 並註釋掉setSize和setLocation行。我仍然沒有看到JApplet中顯示的任何內容。我需要添加其他東西嗎? – prograded 2014-11-03 03:50:05

+0

檢查更新... – MadProgrammer 2014-11-03 03:59:01

+0

add(pane);返回錯誤:java.lang.IllegalArgumentException:將容器的父項添加到自身 – prograded 2014-11-03 04:05:14