打包,但不要让它变小
我有 JFrame
和 GridBagLayout
。用户可以调整该窗口的大小。此外,他还可以执行一些更改窗口大小的编辑操作。我使用 pack(); repaint(); 现在在这些操作之后。但是,实际上我不应该在此类操作后使窗口变小 - 只能变大。我发现的解决方案是
Dimension oldSize = getSize();
pack();
Dimension newSize = window.getSize();
setSize(
(int) Math.max(newSize.getWidth(), oldSize.getWidth()),
(int) Math.max(newSize.getHeight(), oldSize.getHeight()));
repaint();
但我根本不喜欢这个解决方案。除了丑陋的代码之外,我们还设置了两次大小(一次是通过包,一次是直接设置)。还有其他解决方案吗?
I have JFrame
with GridBagLayout
. User can resize this window. Also, he can perform some editing actions that change window size. I use pack(); repaint();
now after such actions. But, actually I shouldn't make window smaller after such operations - only bigger. What I found as solution is
Dimension oldSize = getSize();
pack();
Dimension newSize = window.getSize();
setSize(
(int) Math.max(newSize.getWidth(), oldSize.getWidth()),
(int) Math.max(newSize.getHeight(), oldSize.getHeight()));
repaint();
But I don't like this solution at all. Beside ugly code, we set size twice (once by pack and than directly). Is there any other solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个简单的解决方案是使用这样的东西:
我认为,这不会允许 pack() 使窗口变小,只会变大。
通过在
pack()
之后将最小大小重置为null
,我们可以避免阻止用户随后将其大小调整得更小。最后你不应该需要
repaint()
,大小的改变应该自行触发重绘。 (当然,请确保所有这些操作都发生在事件调度线程中。)A simple solution would be to use something like this:
This will not allow
pack()
to make the window smaller, only bigger, I think.By resetting the minimum size to
null
after thepack()
we avoid preventing the user on resizing it smaller afterwards.You should not need a
repaint()
at the end, the size changing should trigger a repaint by itself. (Of course, make sure that all these actions happen in the event dispatch thread.)Paŭlo 提出的解决方案的另一种解决方案是以下代码:
该解决方案的优点是除非有必要,否则不会调用 pack,并且它避免了我们在使用 Paŭlo 解决方案时在 Linux 上观察到的闪烁。
An alternative solution to the one proposed by Paŭlo is the following code:
The advantage of this solution is that pack isn't called unless it is necessary, and it avoids a flicker we observed on Linux with Paŭlo's solution.
您可以重写 pack() 方法来执行此操作。但不确定是否有更好的方法。
You could override the pack() method to do that. Not sure if there's a better way though.