【发布时间】:2020-08-04 15:17:17
【问题描述】:
我需要以某种方式计算窗户装饰。所以我重写了JDialog 的构造函数。但是当我调用get_decoration_size() 时,它有时会返回错误的值。我的想法是:窗口创建晚于get_decoration_size() 执行(奇怪,因为在同一个线程和同一个构造函数中)。所以我决定睡一会,它奏效了,现在装饰总是有效的。
我的问题是:有没有办法“加入”到创建过程(等到setVisible(true) 显示窗口)?如果是这样,它必须是替换unsafe_sleep(1000)的东西。
package swing.window;
import db.db;
import javax.swing.*;
import java.awt.*;
import static swing.util.*;
import static util.util.unsafe_sleep;
public class calc_decor extends JDialog {
{
//some initializations
setLayout(null);
setResizable(false);
JLabel label = new JLabel("Loading...");
add(label);
setxy(label, 3, 3);
fit(label);
setsize(this, label.getWidth() + 100, label.getHeight() + 100);
window_to_center(this);
setVisible(true);//trying to draw
unsafe_sleep(1000);//without that it looks like get_decoratoin_size()
//is called before setVisible(true)
db.sysdecor = get_decoration_size();//trying to get decorations
dispose();
}
private Dimension get_decoration_size() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
【问题讨论】:
-
“我需要以某种方式计算窗户装饰。” ... 为什么?见What is the XY problem? 一般提示:为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。
-
我之前没有注意到
setLayout(null);.. Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。