简体   繁体   中英

Drawing rectangles with JPanel in Java

What's wrong with the following code? Why isn't the rectangle displaying

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. You don't add the redSquare to the synapseLayer.

  2. Even if you did add the square it would not show because the synapseLayer uses a null layout so the size of that panel is (0, 0). So when you pack the frame there is nothing to show.

Don't use a null layout!!! Let a layout manager determine the size of the panels for you so that the pack() method will work properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM