2013-06-24 61 views
0

以下代碼有什麼問題?爲什麼不顯示在Java中使用JPanel繪製矩形

public class SynapsePermanencesViewer { 

public JPanel createContentPane(Region region) { 
JPanel synapseLayer = new JPanel(); 
synapseLayer.setLayout(null); 

Column[][] columns = region.getColumns(); 

JPanel redSquare = new JPanel(); 
Color color = new Color(128, 0, 0); 
redSquare.setBackground(color); 
int squareLength = 50; 
redSquare.setSize(squareLength, squareLength); 

// calculate the correct location 
redSquare.setLocation(150, 150); // <==== This square isn't displaying WHY??? 

synapseLayer.setOpaque(true); 
return synapseLayer; 
} 

public SynapsePermanencesViewer(Region region) { 
JFrame frame = new JFrame("Synapse Permanences Viewer"); 

frame.setContentPane(this.createContentPane(region)); 

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.pack(); 
frame.setVisible(true); 
} 

public static void main(String[] args) { 
Region parentRegion = new Region("parentRegion", 2, 2, 1, 20, 1); 
Region childRegion = new Region("childRegion", 4, 4, 1, 20, 3); 
RegionToRegionConnect connectType = new RegionToRegionRectangleConnect(); 
connectType.connect(childRegion, parentRegion, 0, 0); 

SynapsePermanencesViewer object = new SynapsePermanencesViewer(parentRegion); 
} 

}

+0

這可能是因爲redSquare沒有被添加到任何要顯示的東西。它只是在本地創建並在方法返回時被GCed。 – jpm

回答

2
  1. 您不要在redSquare添加到synapseLayer的矩形。

  2. 即使添加了正方形,它也不會顯示,因爲synapseLayer使用空白布局,因此該面板的大小爲(0,0)。所以當你打包框架時,沒有什麼可以顯示的。

不要使用null佈局!讓佈局管理器爲你確定面板的大小,以便pack()方法能正常工作。

+0

實際上,它添加時顯示,但我不得不手動拉伸JFrame的大小。 – Humungus

+1

@Humungus,的確,這是您不使用佈局管理器時的問題。 pack()不起作用,因此您需要手動調整框架大小。這不是一個好的設計,用戶會抱怨。 – camickr