开发者

Layouts and minimal sizes

开发者 https://www.devze.com 2023-01-14 17:12 出处:网络
I\'m trying to insert a new panel with a minimal size set 开发者_如何学JAVAonto an existing form. Unfortunately after I do this:

I'm trying to insert a new panel with a minimal size set 开发者_如何学JAVAonto an existing form. Unfortunately after I do this:

this.add(scrap);
this.moveScrapCentre(scrap); // runs setLocation(...)
this.revalidate();
this.repaint();

(where this: JPanel with null layout, scrap: JPanel with box layout and children)

the scrap gets resized to (0,0) - even though I set both minimal and preferred size in Netbeans' property editor. How can I prevent this, apart from forcing scrap.setSize(scrap.getPreferredSize())?


"Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales."—Setting the Layout Manager

Addendum: Oops, I misread the question. Just do

this.setPreferredSize(new Dimension(w, h));

using your desired values of w and h. If this is a spacer, the layout shouldn't matter.

Addendum: Looking yet closer, the size of scrap may be changing dynamically. You can override getPreferredSize() accordingly. As you're using the GUI designer, your panel has a declaration something like this:

public class NewJPanel extends javax.swing.JPanel

You can add the required method inside the class but outside the generated code fold:

@Override
public Dimension getPreferredSize() {
    return new Dimension(w, h);
}

Aside: The GUI designer is an aid that presumes an understanding of the underlying layout manager. Noting requires you to use it for every panel, and many layouts are fairly straightforward. I often see the designer's use reserved for panels needing more complex layouts such as GroupLayout and SpringLayout.

0

精彩评论

暂无评论...
验证码 换一张
取 消