Dimension (Dimension superPreferredSize) { if((myHorizontalMargin > 0) && (myVerticalMargin > 0)){ Dimension screenSize = ScreenUtil.getMainScreenBounds().getSize(); Dimension preferredSize = superPreferredSize; Dimension maxSize = new Dimension(screenSize.width - myHorizontalMargin, screenSize.height - myVerticalMargin); int width = Math.min(preferredSize.width, maxSize.width); int height = Math.min(preferredSize.height, maxSize.height); if(height < preferredSize.height){ width = Math.min(width + 50, maxSize.width); // to disable horizontal scroller } preferredSize = new Dimension(width, height); return preferredSize; } else{ return superPreferredSize; } }