Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Resize JInternalFrame to snap to grid

843806Jul 24 2009 — edited Oct 23 2009
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);

	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 20 2009
Added on Jul 24 2009
16 comments
1,463 views