簡體   English   中英

使用Java中的JPanel繪制矩形

[英]Drawing rectangles with JPanel in Java

以下代碼有什么問題? 為什么不顯示矩形

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);
}

}

  1. 您不會將redSquare添加到synapseLayer。

  2. 即使您確實添加了它也不會顯示的方塊,因為synapseLayer使用空布局,因此該面板的大小為(0,0)。 因此,當您打包框架時,沒有任何東西可以顯示。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM