1 回答
TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
問題是您setPreferredSize在 的構(gòu)造函數(shù)中調(diào)用Component,因此它的大小調(diào)整請求應(yīng)用于框架的內(nèi)容。當(dāng)JFrame創(chuàng)建裝飾時,它會增加該維度。解決方案是將調(diào)用應(yīng)用于setPreferredSize,JFrame例如在initWindow:
public void initWindow(String title, JComponent component)
{
JFrame jf = new JFrame(title);
Toolkit kit = this.getToolkit();
int width = (int) kit.getScreenSize().getWidth();
int height = (int) GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getHeight();
jf.setPreferredSize(new Dimension(width, height));
// ...
}
這是一個演示程序,至少在我的系統(tǒng)上,它重現(xiàn)了問題并演示了解決方案。取消注釋1并注釋掉2會重現(xiàn)該問題。反轉(zhuǎn)注釋掉的行即可解決。
public class FitToScreenDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JComponent component = new JComponent() {};
frame.add(component);
// component.setPreferredSize(getDimensionWithoutTaskBar()); // 1
frame.setPreferredSize(getDimensionWithoutTaskBar()); // 2
frame.pack();
frame.setVisible(true);
}
private static Dimension getDimensionWithoutTaskBar() {
return new Dimension((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth(),
(int) GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getHeight());
}
}
添加回答
舉報
