Java News from Friday, June 3, 2005

In response to yesterday's challenge, Todd Ditchendorf has written a RatioFrame class that maintains a constant ratio. The basic trick seems to be a ComponentListener that sets the size of the frame on resize events:

    protected void addListener() {
        addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent evt) {
                int w = getWidth();
                int h = getHeight();
                if (w > h)
                    setSize(w,(int)(ratio*w));
                else
                    setSize((int)(ratio*h),h);
            }
        });
    }

I'd already tried something similar to this myself, but for whatever reason mine didn't work nearly as smoothly as his does. So far his code only maintains the ratio of the frame, not the ratio of the component within the frame, which is what I really need; but it may be possible to fix it so it does that instead. Ditchendorf also reports that this has problems running in Java 1.4 and on Windows. Fortunately, for this project I can actually accept a solution that only runs in Java 1.5 on the Mac, at least for now. On the other hand, so far when I add this listener to my own program, it locks up so hard I have to reboot the machine (and this on Mac OS X, normally a relatively crash-resistant OS). This might require a lower level solution that doesn't rely on setSize.