2014-11-03 108 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