[英]How do I fix this JFrame resize "bug"?
I made A gui that is (640+200)x640 pixels big.我制作了一个 (640+200)x640 像素大的 gui。 On the left side is a chess board (it is at position 0,0 and has a size of 640x640.The 200 pixels on additional width are ment for some buttons to configure the game etc.左侧是棋盘(位于 position 0,0,尺寸为 640x640。额外宽度上的 200 像素用于一些按钮配置游戏等。
The problem:问题:
The chess board's dimensions always have to be multiples of 8 to fit the frame perfectly.棋盘的尺寸总是必须是 8 的倍数才能完美地适应框架。 If i resize the frame a little bit so that its height increases by 7 pixels, there is a little gap between the chess board and the frame because the squares can't ne drawn in euqal size.如果我稍微调整框架的大小,使其高度增加 7 个像素,则棋盘和框架之间会有一点间隙,因为不能以相等的大小绘制正方形。
What is a clever way to fix this?有什么聪明的方法可以解决这个问题?
I assume you use Swing or AWT, using Frame
or JFrame
or Window
or JWindow
as the window you're working in. I assume you use Swing or AWT, using Frame
or JFrame
or Window
or JWindow
as the window you're working in.
Step 1) Put your chessboard into its own JPanel
.第 1 步)将您的棋盘放入自己的JPanel
中。 Let's call that class ChessBoardPanel
.我们称之为 class ChessBoardPanel
。
Step 2) Set the ChessBoardPanel
's minimum, preferred and maximum sizes to the sizes you wish for in its constructor (or put it in a method if you wanna check the resize event of the parent and react to that, adjusting in 8px steps for bigger/smaller parent window.)步骤 2) 将ChessBoardPanel
的最小、首选和最大尺寸设置为您在其构造函数中希望的尺寸(或者如果您想检查父级的调整大小事件并对此做出反应,则将其放入方法中,以 8px 的步长调整更大/更小的父 window。)
Step 3) Install a LayoutManager in the Window ( window.setLayout(...)
), like BoderLayout
步骤 3) 在 Window ( window.setLayout(...)
) 中安装一个 LayoutManager,例如BoderLayout
Step 4) Create a new instance of the ChessBoardPanel
: ChessBoardPanel myChessBoardPanel = new ChessBoardPanel(parentWindow)
;步骤 4) 创建 ChessBoardPanel 的新实例: ChessBoardPanel ChessBoardPanel
ChessBoardPanel myChessBoardPanel = new ChessBoardPanel(parentWindow)
;
Step 5) Add it to the parent window, maybe indicating layout behavior.步骤 5) 将其添加到父 window,可能表示布局行为。 For example, if you went with the BorderLayout
, add it like this in the parent window: this.add(myChessBoardPanel, BorderLayout.WEST);
例如,如果您使用BorderLayout
,请在父级 window 中添加这样的内容: this.add(myChessBoardPanel, BorderLayout.WEST);
so it will always be displayed on the left.所以它会一直显示在左边。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.