Code Hackery #1: Map Resize Dialog

In an effort to pump out more posts and make this website less of a dead-zone, I’m going to try and create a weekly post with a bit of code I have managed to hack together that works perfectly against all odds.


First up is this Map Resize Dialog I created for the WPlanner rewrite I completed a couple of weeks ago. For those that had used the old WPlanner build, the resize dialog was a bit empty. All it had were 4 spinners for each cardinal direction, and a label stating the new size.

When I was rewriting it for the new version, I decided to bite the bullet and design it the way I wanted it originally (but couldn’t be f’d at the time to do) since I had Eclipse’s nifty new Swing GUI builder to use. The idea was pretty simple: each spinner (north, south, east and west) are put in their appropriate positions in the dialog with the central area in between them all being taken up by a preview box, showing the old map size and the new one.

Simple idea right? I thought so too, until I got to the preview image part. Problem was I had a specific area to work with, in this case that area was 160×160 pixels. If the map was too small, you couldn’t really tell what the preview was. If the map was too large, the whole area would just show the same image.

So my solution was to take the max width/height from both the new and old map, put them together to get the true max width/height between them, calculate a scale to apply to the sizes so everything would fix in the preview area, then apply that scale to everything. Add to that a lot of hackery to get the image centered on the 160×160 area no matter what, and you have a beautiful bit of hacked code:

previewPanel = new JPanel() {
private static final long serialVersionUID = 8044822007565570911L;

public void paint(Graphics g) {

int xMax = 160, yMax = 160;

int newW = initW + westAdj + eastAdj;
int newH = initH + northAdj + southAdj;

float tSizeW = xMax / (newW > initW ? newW : initW);
float tSizeH = yMax / (newH > initH ? newH : initH);
float tSize = (tSizeW < tSizeH ? tSizeW : tSizeH); int newX = (int) ((xMax - (newW * tSize)) / 2); int newY = (int) ((yMax - (newH * tSize)) / 2); int initX = (int) (newX + (westAdj * tSize)); int initY = (int) (newY + (northAdj * tSize)); if (initX < 0) { newX -= initX; initX -= initX; } if (initY < 0) { newY -= initY; initY -= initY; } if (((int) tSize) g.setColor(Color.BLACK); g.drawString("Preview Unavailable", 20, 50); return; } g.setColor(Color.GREEN); g.fillRect(initX, initY, (int) (initW * tSize), (int) (initH * tSize)); g.setColor(new Color(255, 0, 0, 100)); g.fillRect(newX, newY, (int) (newW * tSize), (int) (newH * tSize)); } }; previewPanel.setPreferredSize(new Dimension(160, 160));[/java]   You can view the full file here:

Tagged , , , , , . Bookmark the permalink.

Leave a Reply