且构网

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

在JFrame中将固定大小的画布居中

更新时间:2023-12-05 18:07:16

JPanel固定为用户可能指定的任何大小,并居中居中,并且滚动条的行为符合人们的预期

JPanel fixed in whatever size the user might have specified and centered in the middle as well as the scrollbars behaving as one would expect

因此,您需要嵌套面板,以便可以以其首选的尺寸显示画布面板,而父面板将根据框架的尺寸进行调整.

So you need to nest panels so the canvas panel can be displayed at its preferred size, while the parent panel resizes with the size of the frame.

使用GridBagLayoutJPanel是实现此目的的简单方法.然后,使用默认的GridBagConstraints将画布面板添加到该面板.

An easy way to do this is with a JPanel that uses a GridBagLayout. Then you add the canvas panel to this panel using the default GridBagConstraints.

因此,面板的基本结构为:

So the basic structure of the panels would be:

JPanel canvas = new JPanel();
canvas.setPreferredSize( new Dimension(300, 300) );
canvas.setBackground(Color.RED);

JPanel wrapper = new JPanel( new GridBagLayout() );
wrapper.add(canvas, new GridBagConstraints() );

frame.add(new JScrollPane(wrapper));

注意:不需要您的"masterPanel". JFrame内容窗格的默认布局管理器是BorderLayout,因此您只需将"menuPanel"和"scrollPane"直接添加到具有适当BorderLayout约束的框架中即可.

Note: there is no need for your "masterPanel". The default layout manager for the content pane of a JFrame is a BorderLayout, so you just add the "menuPanel" and "scrollPane" directly to the frame with the proper BorderLayout constraints.