Java ComponentResized - 检测是用户调整了窗口大小还是以编程方式调整了窗口大小 [英] Java ComponentResized - Detect whether user resized the window or it was resized programatically

查看:69
本文介绍了Java ComponentResized - 检测是用户调整了窗口大小还是以编程方式调整了窗口大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JFrame,我可以在其中删除和添加组件,每次执行此操作时,我都会相应地调整框架的大小.我添加了一个组件侦听器,但当然它会由用户调整窗口大小和我的 setSize() 方法触发.
有什么方法可以从 ComponentEvent 中查看是用户调整了窗口大小还是我通过 setSize() 调整了窗口大小?
我找到的可能解决方案是:
1. 使用一个标志 - 布尔调整大小 - 我在 setSize() 之前将其设置为 true,之后设置为 false.
2. 添加 mouseDragged 监听器,比较拖动前后的大小.
第二个绝对不是一个好的选择.第一个可行,但我想知道是否可以通过简单的方式找到用户是否是调整窗口大小的人.

I have a JFrame in which I remove and add components and each time I do this, I resize the frame accordingly. I added a Component Listener but of course it gets triggered both by the user resizing the window and also by my setSize() methods.
Is there any way to see from the ComponentEvent whether the user resized the window or I did through setSize()?
The posible solutions I found are:
1. Use a flag - boolean resizing - which I set to true before setSize() and to false after that.
2. Add a mouseDragged listener and compare sizes before and after the drag.
The second one is definitely not a good choice. The first one would work but I would like to know if I can find in a simple way whether the user is the one who resized the window or not.

推荐答案

我相应地调整了框架的大小

I resize the frame accordingly

使用 pack() 有什么问题?

Whats wrong with using pack()?

我删除和添加组件,每次这样做时,

I remove and add components and each time I do this,

那么您应该在此处设置布尔值:

Then this is where you should set your Boolean value:

programResize == true:
panel.add(...);
frame.setSize(...); // this should cause the ComponentListener to fire
// the ComponentListener would then use programResize == false;

或者更好的选择可能是:

Or a better option option could be:

component.removeComponentListener(...);
panel.add(...);
frame.setSize(...);
component.addComponentListener(...);

我更喜欢这种方法,因为所有基于手动更新的逻辑都包含在一个地方,不需要定义布尔变量.

I like this approach better because all the logic based on the manual update is self contained in one place and there is no need to define a Boolean variable.

这篇关于Java ComponentResized - 检测是用户调整了窗口大小还是以编程方式调整了窗口大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆