I have created a JPanel within a JPanel, and I would like to set its width and height attribute to some specific numbers. here is what I have so far.
searchPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
searchPanel.setBorder(BorderFactory.createCompoundBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED), new EmptyBorder(12, 12, 12, 12)));
c.insets = new Insets(2, 2, 2, 2);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 1;
c.gridx = 0;
c.gridy = 0;
searchPanel.add(typeLabel, c);
c.weightx = .8;
c.weighty = 1;
c.gridx = 0;
c.gridy = 1;
searchPanel开发者_如何学Go.add(typeComboBox, c);
....
yearComboBox.setModel(this.yearDefaultCombo);
typeComboBox.setModel(this.typeDefaultCombo);
updateYearComboBox();
this.setLayout(new BorderLayout(10, 10));
this.setBorder(new EmptyBorder(10, 10, 10, 10));
searchPanel.setSize(200, 100);
this.add(searchPanel, BorderLayout.NORTH);
In the code, "this" refers to the parent JPanel. Right now my inner "searchPanel" is stretched along the entire top section of the screen due to the BorderLayout.NORTH constraint, but I only want it as a little panel in the left top corner however setSize didn't work for me.
thanks.
Most layout managers respect preferred size more than size, and so you may with to try setPreferredSize(...) on your JPanel. But no matter what you do, if you add it BorderLayout.NORTH, it will stretch to fill the entire north position of the containing JPanel. You may wish to nest your searchPanel into another JPanel (perhaps one using BoxLayout), and add that JPanel BorderLayout.NORTH.
Please read the layout tutorials and their API's as most of this is explained there.
精彩评论