且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPanel 显示为一个小白框

更新时间:2023-12-05 09:34:40

基本上,这是对 Swing API 工作方式的误解.

Basically, it's a misunderstanding of how the Swing API works.

Swing(严重)依赖于布局管理 API,该 API 用于决定组件应该有多大(以及应该放置在哪里)

Swing relies (heavily) on the layout management API which is used to make decisions about how large components should be (and where they should be placed)

使用 setSize 是没有意义的,因为布局管理器会自行决定它认为组件的大小应该是什么,并会相应地进行调整.

Using setSize is pointless, as the layout manager will make it's own decisions about what it thinks the size of your component should be and will adjust it accordingly.

例如,您可以使用getPreferred/Minimum/MaximumSize向布局管理器提出您希望组件有多大的建议

You can make suggestions to the layout manager about how large you'd like the component to be using getPreferred/Minimum/MaximumSize, for example

public class PaintPanel extends JPanel
{

    public PaintPanel()
    {
        super();
        setBackground(Color.WHITE);
    }

    public Dimension getPreferredSize() {
        return new Dimension(700, 400);
    }
}

请记住,布局管理器完全有权忽略这些值,因此您需要更好地了解这些管理器的工作原理

Just remember, layout managers are well within their right to ignore these values, so you need to have a better understanding of how these managers work

有关详细信息,请参阅在容器内布置组件