I wanted a JIntermal Frame that would resize and move according to some grid size so that users could create a nice, ordered set of windows (these will ultimately be mini-reports or tables). The moving works fine, but the resizing only partially works. I added a ComopnentListener to a JInternalFrame and then wrote some code to get the size of the frame whenever it is resized and round off that amount to some snap size. It works perfectly if resizing to the bottom or right, but if you resize to the left or top, the opposite side of the frame also moves. The result is that you can end up with a frame that is sized in the correct increment, but not positioned on the underlying grid correctly. I tried to trace through where the UI (BasicInternalFrameUI?) is causing this effect, but no luck. It's easier to see then explain, so here's the code isolating just the resizing problem:
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
public class FrameSnap {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocation(50,50);
frame.setVisible(true);
JDesktopPane desk = new JDesktopPane();
JInternalFrame snapFrame = new JInternalFrame();
snapFrame.setSize(200, 200);
snapFrame.setVisible(true);
snapFrame.setResizable(true);
snapFrame.setLocation(100,100);
snapFrame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
JInternalFrame frame = (JInternalFrame) e.getSource();
int snapSize = 20;
int width = frame.getWidth();
int height = frame.getHeight();
//Round off resized dimensions to snap size
width = ((width + snapSize/2)/snapSize) * snapSize;
height = ((height + snapSize/2)/snapSize) * snapSize;
//Snaps resize to implicit grid, but doesn't
//work right if resizing to the left or up
frame.setSize(width, height);
}
});
desk.add(snapFrame);
frame.add(desk);
}
}