Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

java - JDialog doesn't respect dimensions of child components

I have a setup that usually works, but I'm finding it a bit of a pain at the moment.

I have a JDialog (formerly a JFrame, but I've changed the UI flow recently to remove redundant JFrames) set to BorderLayout that contains three main JPanels, header, content and footer.

The header JPanel has a background image that is loading fine. However, I'm calling all manner of setMinimumSize / setPreferredSize / etc (I even tried setSize and setBounds out of desperation) and the JPanel isn't being sized correctly. The layout for that component is BoxLayout, and the children sit comfortably within it, but that shouldn't affect what I'm trying to do with the header panel itself.

The only thing that works is setting a size on the parent JDialog. But I don't want to do that / from what I've read it seems like bad design. I'd also have to maths out the potential width / height of all the children, add the margins, etc.

Advice I am not looking for: "use a different LayoutManager."

I want to understand if there's a reason for the child components not being respected.

I can provide code, but isolating a small, runnable segment is difficult given the amount of interlocked systems I'm juggling. Here is the relevant snippet to set the size of the JPanel. The image dimensions are 480 * 96.

public JPanelThemed(BufferedImage image) {
    super();
    this.backgroundImage = image;
    setAllSimilarConstraints(new Dimension(image.getWidth(), image.getHeight()));
    setOpaque(false);
}

// for use with BoxLayout as it requires explicit bounds to be set
public void setAllSimilarConstraints(Dimension dim) {
    setPreferredSize(dim);
    setMinimumSize(dim);
    setMaximumSize(dim);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would implement it a bit another way - to ensure that preferred/min/max/Size can not be changed from elsewhere:

public JPanelThemed(BufferedImage image) {
    this.backgroundImage = image;
    setOpaque(false);
}

public Dimension getPreferredSize() {
    return new Dimension(this.backgroundImage.getWidth(), this.backgroundImage.getHeight());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...