我的Java Swing应用程序在用户调整了jFrame的大小之后,使用updateUiChanged()来调整字体的大小。但是,当jFrame最小化然后最大化时会触发updateUiChanged(),这会导致问题
我试图用以下方法捕获最小化和最大化事件,但它们根本不执行,或者它们在updateUiChanged()之后执行,为时已晚。
如何在updateUiChanged()之前捕获最小化和最大化
请参见下面的updateUiChanged实现。
谢谢
private WindowListener wndMinMax;
wndMinMax = new WindowAdapter(){
public void windowIconified(WindowEvent e){
if(debug)debug("Window Iconfied!!");
return;
}
public void windowDeiconified(WindowEvent e){
if(debug)debug("Window DeIconfied!!");
return;
}
};
this.addWindowListener(wndMinMax);
addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e) //V.43
{
if (e.getSource() instanceof JFrame) //V.43
{
updateUiChanged((int) e.getComponent().getWidth(),
(int) e.getComponent().getHeight());
}
}
});
最佳答案
您可以使用EventQueue.invokeLater来确保您的updateUiChanged调用发生在WindowEvent之后。您可以在私有实例字段中跟踪WindowEvent的发生,因此延迟的ComponentListener代码可以知道调整大小是否与WindowEvent配对:
private boolean iconifyStateChanged;
// ...
wndMinMax = new WindowAdapter(){
public void windowIconified(WindowEvent e){
if(debug)debug("Window Iconfied!!");
iconifyStateChanged = true;
}
public void windowDeiconified(WindowEvent e){
if(debug)debug("Window DeIconfied!!");
iconifyStateChanged = true;
}
};
this.addWindowListener(wndMinMax);
addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e) //V.43
{
if (e.getSource() instanceof JFrame) //V.43
{
// This will run after any pending WindowEvents.
EventQueue.invokeLater(() -> {
if (!iconifyStateChanged)
{
updateUiChanged(e.getComponent().getWidth(),
e.getComponent().getHeight()));
}
iconifyStateChanged = false;
});
}
}
});
(getWidth()和getHeight()已经返回int值,因此不需要强制转换为int。)
关于java - 如何在updateUiChanged()事件之前捕获Java windowIconified()和windowIDeconified()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51639378/